I donβt know if there is an official name for this, but I played with what I like to call the "self-factory" template. Basically, this is when an abstract base class acts like a factory for itself. Let me explain:
I have Foo objects and Bar objects on my system that are used through the FooInterface and BarInterface interfaces. I need to give my clients the correct type of Foo and Bar. The decision about which specific Foo object to create is created at compile time. For example, if you are compiling on win32, you want to create only Win32Foo objects, and when compiling on OSX you want to create only OSXFoo objects, etc. But a solution for which a specific Bar object is created is created at runtime based on the key string.
Now, my question is the best way to implement this scheme. One of the ways I came up with is using regular factories:
shared_ptr<FooInterface> foo = FooFactory::create();
shared_ptr<BarInterface> happyBar = BarFactory::create("Happy");
shared_ptr<BarInterface> sadBar = BarFactory::create("Sad");
Another way is to use what I call "car factories":
shared_ptr<FooInterface> foo = FooInterface::create();
shared_ptr<BarInterface> happyBar = BarInterface::create("Happy");
shared_ptr<BarInterface> sadBar = BarInterface::create("Sad");
What are the pros and cons of each approach, both in terms of ease of use and in terms of architecture?
cwick source
share