In software engineering, Creational Design Patterns deal with object creation mechanisms, i.e. try to create objects in a manner suitable to the situation. In addition to this basic or ordinary form of object creation could result in design problems or added complexity to the design. Factory Design Pattern in C++ helps to mitigate this issue by . creating objects using separate methods or polymorphic classes By the way, If you haven’t check out my other articles on Creational Design Patterns, then here is the list: Factory Builder Prototype Singleton The code snippets you see throughout this series of articles are simplified not sophisticated. So you often see me not using keywords like override, final, public(while inheritance) just to make code compact & consumable (most of the time) in single standard screen size. I also prefer struct instead of class just to save line by not writing “public:” sometimes and also miss , constructor, , prefix std::, deleting dynamic memory, intentionally. virtual destructor copy constructor I also consider myself a pragmatic person who wants to convey an idea in the simplest way possible rather than the standard way or using Jargons. Note: If you stumbled here directly, then I would suggest you go through first, even if it is trivial. I believe it will encourage you to explore more on this topic. What is design pattern? All of this code you encounter in this series of articles are compiled using C++20(though I have used features up to C++17 in most cases). So if you don’t have access to the latest compiler you can use which has preinstalled boost library as well. Modern C++ https://wandbox.org/ Intent For the creation of wholesale objects unlike builder(which creates piecewise). Motivation Let say you have a Point class having x & y as co-ordinates which can be Cartesian or Polar coordinate as below: Point( x, y){ } }; { struct Point float float /*...*/ // Cartesian co-ordinates // Not OK: Cannot overload with same type of arguments // Point(float a, float b){ /*...*/ } // Polar co-ordinates // ... Implementation This isn't possible as you might know you can not create two constructors with the same type of arguments. Other way around is: cartesian, polar }; Point( a, b, PointTypetype = PointType::cartesian) { (type == PointType::cartesian) { x = a; b = y; } { x = a * (b); y = a * (b); } } }; enum { class PointType { class Point float float if else cos sin But this isn't a sophisticated way of doing this. Rather we should delegate separate instantiation to separate methods. Factory Design Pattern Examples in C++ So as you can guess. We are going to mitigating constructor limitation by moving the initialization process from constructor to other structure. And we gonna be using the Factory Method for that. And just as the name suggests it uses the method or member function to initialize the object. Factory Method cartesian, polar }; m_x; m_y; PointType m_type; Point( x, y, PointType t) : m_x{x}, m_y{y}, m_type{t} {} : ostream & <<(ostream &os, Point &obj) { os << << obj.m_x << << obj.m_y; } { {x, y, PointType::cartesian}; } { {a * (b), a * (b), PointType::polar}; } }; { p = Point::NewPolar( , M_PI_4); << p << ; EXIT_SUCCESS; } enum { class PointType { class Point float float // Private constructor, so that object can't be created directly const float const float public friend operator const return "x: " " y: " Point static NewCartesian ( x, y) float float return Point static NewPolar ( a, b) float float return cos sin int main () // Point p{ 1,2 }; // will not work auto 5 cout endl // x: 3.53553 y: 3.53553 return As you can observe from the implementation. It actually disallows the use of constructor & forcing users to use static methods instead. And this is the essence of the . Factory Method i.e. private constructor & static method Classical Factory Design Pattern If you have dedicated code for construction then while not we move it to a dedicated class. And Just to do separation of concerns i.e. from SOLID design principles. Single Responsibility Principle }; : { { x, y }; } { { r* (theta), r* (theta) }; } }; { class Point // ... as it is from above friend ; class PointFactory { class PointFactory public Point static NewCartesian ( x, y) float float return Point static NewPolar ( r, theta) float float return cos sin Mind that this is not the abstract factory this is a concrete factory. Making the PointFactory friend class of Point we have violated the (OCP). As friend keyword itself contrary to OCP. Open-Closed Principle Inner Factory There is a critical thing we missed in our Factory that there is no strong link between PointFactory & Point which confuses user to use Point just by seeing everything is private. So rather than designing a factory outside the class. We can simply put it in the class which encourage users to use Factory. Thus, we also serve the second problem which is breaking the . And this will be somewhat more intuitive for the user to use Factory. Open-Closed Principle m_x; m_y; Point( x, y) : m_x(x), m_y(y) {} : { { x,y }; } { { r* (theta), r* (theta) }; } }; }; { p = Point::Factory::NewCartesian( , ); EXIT_SUCCESS; } { class Point float float float float public { struct Factory Point static NewCartesian ( x, y) float float return Point static NewPolar ( r, theta) float float return cos sin int main () auto 2 3 return Abstract Factory do we need an Abstract Factory? Why C++ has the support of polymorphic object destruction using it’s base class’s . Similarly, equivalent support for creation & copying of objects is missing as С++ doesn’t support & . virtual destructor virtual constructor copy constructors Moreover, you can’t create an object unless you know its static type, because the compiler must know the amount of space it needs to allocate. For the same reason, copy of an object also requires its type to known at compile-time. ~Point(){ << ; } }; Point { ~Point2D(){ << ; } }; Point { ~Point3D(){ << ; } }; { who; } { struct Point virtual cout "~Point\n" : struct Point2D cout "~Point2D\n" : struct Point3D cout "~Point3D\n" void who_am_i (Point *who) // Not sure whether Point2D would be passed here or Point3D // How to `create` the object of same type i.e. pointed by who ? // How to `copy` object of same type i.e. pointed by who ? delete // you can delete object pointed by who, thanks to virtual destructor Example of Abstract Factory Design Pattern The Abstract Factory is useful in a situation that requires the creation of many different types of objects, all derived from a common base type. The Abstract Factory defines a method for creating the objects, which can then override to specify the derived type that will be created. Thus, at run time, the appropriate Abstract Factory Method will be called depending upon the type of object referenced/pointed & return a base class pointer to a new instance of that object. subclasses ~Point() = ; <Point> create() = ; <Point> clone() = ; }; Point { <Point> create() { make_unique<Point2D>(); } <Point> clone() { make_unique<Point2D>(* ); } }; Point { <Point> create() { make_unique<Point3D>(); } <Point> clone() { make_unique<Point3D>(* ); } }; { new_who = who->create(); duplicate_who = who->clone(); who; } { struct Point virtual default virtual unique_ptr 0 virtual unique_ptr 0 : struct Point2D unique_ptr return unique_ptr return this : struct Point3D unique_ptr return unique_ptr return this void who_am_i (Point *who) auto // `create` the object of same type i.e. pointed by who ? auto // `copy` the object of same type i.e. pointed by who ? delete As shown above, we have leveraged polymorphic methods by delegating the act of creation & copying the object to the derived class through the use of pure virtual methods. Above code is not only implement (i.e. create()) but also implements (i.e. clone()). virtual constructor virtual copy constructor Make sure while using Abstract Factory you have ensured the . Liskov's Substitution Principle(LSP) Functional Approach to Factory Design Pattern using Modern C++ In our Abstract Factory example, we have followed the object-oriented approach but its equally possible nowadays to a more functional approach. So, let's build a similar kind of Factory without relying on polymorphic functionality as it might not suit some time-constrained application like an . Because the may troll system during critical functionality. embedded system virtual table & dynamic dispatch mechanism This is pretty straight forward as it uses functional & as follows: lambda functions }; Point { }; Point { }; <PointType, function< <Point>() >> m_factories; : PointFunctionalFactory() { m_factories[PointType::Point2D] = [] { make_unique<Point2D>(); }; m_factories[PointType::Point3D] = [] { make_unique<Point3D>(); }; } <Point> create(PointType type) { m_factories[type](); } }; { PointFunctionalFactory pf; p2D = pf.create(PointType::Point2D); EXIT_SUCCESS; } { struct Point /* . . . */ : struct Point2D /* . . . */ : struct Point3D /* . . . */ { class PointFunctionalFactory map unique_ptr public return return unique_ptr return int main () auto return If you are thinking that we are over-engineering, then keep in mind that our object construction is simple here just to demonstrate the technique & so does our lambda function. When your object representation increases, it requires a lot of methods to call in order to instantiate object properly, in such case you just need to modify lambda expression of the factory or introduce . Builder Design Pattern Benefits of Factory Design Pattern Single point/class for different object creation. Thus easy to maintain & understand software. You can create the object without even knowing its type by using Abstract Factory. It provides great modularity. Imagine programming a video game, where you would like to add new types of enemies in the future, each of which has different AI functions and can update differently. By using a factory method, the controller of the program can call to the factory to create the enemies, without any dependency or knowledge of the actual types of enemies. Now, future developers can create new enemies, with new AI controls and new drawing member functions, add it to the factory, and create a level which calls the factory, asking for the enemies by name. Combine this method with an XML description of levels, and developers could create new levels without having to recompile their program. All this, thanks to the separation of creation of objects from the usage of objects. Allows you to change the design of your application more readily, this is known as loose coupling. Summary by FAQs Abstract Factory & Functional Factory is always a good choice. What is the correct way to implement the Factory Design Pattern in C++? Factory vs Abstract Factor vs Functional Factory? Factory: Create an object with varied instantiation. Abstract Factor: Create an object without knowing its type & refer using base class pointer & reference. Access using polymorphic methods. Functional Factory: When object creation is more complex. Abstract Factory + . Although I have not included Builder in Functional Factory example. Builder Design Pattern What's the difference between Abstract Factory and Builder Design Pattern? Factory produces the objects in wholesale that could be any object from inheritance hierarchy(like Point, Point2D, Point3D). While Builder deals with instantiation of an object that is limited to a single object(Although this statement is still debatable). You see Factory is all about wholesale object creation while the builder is piecewise object creation. In both the patterns, you can separate out the mechanism related to object creation in other classes. When to use the Factory Design Pattern? Employ Factory Design Pattern to create an object of required functionality(s) but type of object will remain undecided or it will be decided ob dynamic parameters being passed. Previously published at http://www.vishalchovatiya.com/factory-design-pattern-in-modern-cpp/