Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Hopefully, 76 lines of code speak more than a few words - (using C++11 version of these features instead of the boost ones, but they're pretty much the same anyway)</p> <p>I would put the definition of the <em>factory(ies)</em> and the definition of the <em>creators</em> in the same (or nearby) scope, so that each of the creators can "see" any of their dependent factories - avoiding the need to pass factories around too much, and avoiding singletons</p> <p>Cars &amp; Sirens:</p> <pre><code>class ISiren {}; class Siren : public ISiren { public: Siren() { std::cout &lt;&lt; "Siren Created" &lt;&lt; std::endl; } }; class ICar{}; class EstateCar : public ICar { public: EstateCar() { std::cout &lt;&lt; "EstateCar created" &lt;&lt; std::endl;} }; class PoliceCar : public ICar { std::shared_ptr&lt;ISiren&gt; siren; public: PoliceCar( std::shared_ptr&lt;ISiren&gt; siren) : siren( siren ) { std::cout &lt;&lt; "PoliceCar created" &lt;&lt; std::endl; } }; </code></pre> <p>Factories:</p> <pre><code>typedef std::function&lt; std::shared_ptr&lt;ICar&gt; () &gt; CreatorType; class CarFactory { std::map&lt;std::string, CreatorType&gt; creators; public: void AddFactory( std::string type, CreatorType func ) { creators.insert( std::make_pair(type, func) ); } std::shared_ptr&lt;ICar&gt; CreateCar( std::string type ) { CreatorType&amp; create( creators[type] ); return create(); } }; class SirenFactory { public: // Simple factory creating 1 siren type just for brevity std::shared_ptr&lt;ISiren&gt; CreateSiren() { return std::make_shared&lt;Siren&gt;(); } }; </code></pre> <p>"Factory Root" (main function, wherever factories are defined) :</p> <pre><code>int main() { CarFactory car_factory; // Car factory unaware of Siren factory SirenFactory siren_factory; auto EstateCarLambda = []() { return std::make_shared&lt;EstateCar&gt;(); }; // Estate car lambda knows nothing of the Siren Factory auto PoliceCarLambda = [&amp;siren_factory]() { return std::make_shared&lt;PoliceCar&gt;( siren_factory.CreateSiren() ); }; // Police car creation lambda using the Siren Factory car_factory.AddFactory( "EstateCar", EstateCarLambda ); car_factory.AddFactory( "PoliceCar", PoliceCarLambda ); std::shared_ptr&lt;ICar&gt; car1 = car_factory.CreateCar( "EstateCar" ); std::shared_ptr&lt;ICar&gt; car2 = car_factory.CreateCar( "PoliceCar" ); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload