Wiring Idiom in C++

12 Feb 2016

Neil Conway wrote a little C program in order to answer a question. I wrote previously about it, but today, in order to practice TDD and to learn Google Test, I rewrote it in C++.

You could read it, but I have to say it's mostly not that interesting.

The only interesting part (from my perspective) is an example of what I would call "the wiring idiom", though it might be the same thing as what other people call "Mediator Pattern" or "Facade Pattern" or "Compositional Chain".

Basically, you idea is that you have a single object that creates, owns, and wires together a network of simple objects. In this case the network is a simple pipeline, but it can be an arbitrary graph. The limitation is that if you want to make cyclic graphs, then the objects in the cycle cannot use their collaborators immediately - since they might not be constructed yet.

// Copyright 2016 IDEXX
#include "dataflow_bench_in_cpp/benchmark.h"
#include <set>

// Constructor
Benchmark::Benchmark()
  : sink(),
    p4(4, &sink),
    p6(6, &p4),
    j1(&p6),
    p8(8, &j1),
    p10(10, &p8),
    j2(&p10) {
  for (int i = 0; i < 12000; i += 1) {
    if (i%2 == 0) {
      j1.Add(i);
      j2.Add(i);
    }
  }
}

void Benchmark::Run() {
  for (int i = 0; i < 2000000; i += 1) {
    if (i%2 == 1) {
      j2.Invoke(i);
    }
  }
}