Code/Recipes/God patterns

From Polytech Center Barcelona
Jump to: navigation, search

Dependency Injection

Often have we have a context or special component, and several components which depend on it.

Useful for storing resources. For example initializing values.

For example: a threadpool might start 8 threads, and then several services can depend on that threadpool.

threadpool pool(8);
networking net(pool);
protocol prot(net);

// Have a separate threadpool for the filesystem
threadpool pool(4);
database db(pool);

Longer example:

struct god
{
};

struct earth
{
    earth(god& g);
    god& g_;
};

struct sun
{
    sun(god& g);
    god& g_;
};

earth::earth(god& g)
  : g_(g)
{
}

sun::sun(god& g)
  : g_(g)
{
}

int main()
{
    god g;
    earth e(g);
    sun s(g);
    return 0;
}

Reference is important otherwise you get different copies

struct god
{
};

struct earth
{
    earth(god g);
    god g_;
};

struct sun
{
    sun(god g);
    god g_;
};

earth::earth(god earth_god)
  : g_(g)
{
}

sun::sun(god sun_god)
  : g_(g)
{
}

int main()
{
    god templ;
    // These constructors accept by value so they create their own
    // earth and sun god copies of the template god.
    earth e(templ);
    sun s(templ);
    return 0;
}

Polytheism pattern

#include <string>
#include <vector>

struct god
{
    god(const std::string& name);
    const std::string name;
};

using gods_list = std::vector<god>;

struct earth
{
    earth(gods_list& gods);
    gods_list& gods_;
};

struct sun
{
    sun(gods_list& gods);
    gods_list& gods_;
};

god::god(const std::string& name)
  : name(name)
{
}

earth::earth(gods_list& gods)
  : gods_(gods)
{
}

sun::sun(gods_list& gods)
  : gods_(gods)
{
}

int main()
{
    // Earth and sun have multiple different gods

    gods_list earth_gods = {god("x"), god("y"), god("z")};
    earth e(earth_gods);

    gods_list sun_gods = {god("a"), god("b"), god("c")};
    sun s(sun_gods);
    return 0;
}