Self-Factory Template

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?

+3
source share
3 answers

Factories have two common uses:

1) Decide on a dynamic polymorphic type at runtime based on parameters and / or global state (e.g. configuration). Your template does this.

2) : factory, , factory, . . , ( , factory ), factory .

, ( ) , . FooInterface, FooInterface:: create(). , , , , .

+2

:

shared_ptr<FooInterface> foo = Factory<FooInterface>::create();
shared_ptr<BarInterface> happyBar = Factory<BarInterface>::create("Happy");
shared_ptr<BarInterface> sadBar = Factory<BarInterface>::create("Sad");

:

template <class I>
struct Factory { };

, factory, :

template <>
struct Factory<FooInterface>
{
    static FooInterface create();
};

factory , .

+3

. , Win32Factory, OSXFactory .. , (win32/unix/etc) - factory, , .

If you have only two classes (Foo and Bar), I'm not sure if it's worth trying to create factories for them, and not just use the method createfor interfaces.

Oh, and when the interface has a way to create objects of this type, it calls the factory method template .

+1
source

Source: https://habr.com/ru/post/1711215/


All Articles