# C++ Programming/Code/Design Patterns/Creational Patterns
## Creational Patterns

In software engineering, creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or added complexity to the design. Creational design patterns solve this problem by somehow controlling this object creation.
In this section we assume that the reader has enough familiarity with functions, global variables, stack vs. heap, classes, pointers, and static member functions as introduced before.
As we will see there are several creational design patterns, and all will deal with a specific implementation task, that will create a higher level of abstraction to the code base, we will now cover each one.

### Builder

The Builder Creational Pattern is used to separate the construction of a complex object from its representation so that the same construction process can create different objects representations.

#### Problem

    We want to construct a complex object, however we do not want to have a complex constructor member or one that would need many arguments.

#### Solution

    Define an intermediate object whose member functions define the desired object part by part before the object is available to the client. Builder Pattern lets us defer the construction of the object until all the options for creation have been specified.
You can also use the latest version c++17 standard

### Factory

Definition: A utility class that creates an instance of a class from a family of derived classes

### Abstract Factory

Definition: A utility class that creates an instance of several families of classes. It can also return a factory for a certain group.
The Factory Design Pattern is useful in a situation that requires the creation of many different types of objects, all derived from a common base type. The Factory Method defines a method for creating the objects, which subclasses can then override to specify the derived type that will be created. Thus, at run time, the Factory Method can be passed a description of a desired object (e.g., a string read from user input) and return a base class pointer to a new instance of that object. The pattern works best when a well-designed interface is used for the base class, so there is no need to cast the returned object.

#### Problem

    We want to decide at run time what object is to be created based on some configuration or application parameter. When we write the code, we do not know what class should be instantiated.

#### Solution

    Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
In the following example, a factory method is used to create laptop or desktop computer objects at run time.
Let's start by defining Computer, which is an abstract base class (interface) and its derived classes: Laptop and Desktop.
The actual ComputerFactory class returns a Computer, given a real world description of the object.
Let's analyze the benefits of this design. First, there is a compilation benefit. If we move the interface Computer into a separate header file with the factory, we can then move the implementation of the NewComputer function into a separate implementation file. Now the implementation file for NewComputer is the only one that requires knowledge of the derived classes. Thus, if a change is made to any derived class of Computer, or a new Computer subtype is added, the implementation file for NewComputer is the only file that needs to be recompiled. Everyone who uses the factory will only care about the interface, which should remain consistent throughout the life of the application.
Also, if there is a need to add a class, and the user is requesting objects through a user interface, no code calling the factory may be required to change to support the additional computer type. The code using the factory would simply pass on the new string to the factory, and allow the factory to handle the new types entirely.
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.
Another example:

### Prototype

A prototype pattern is used in software development when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used, for example, when the inherent cost of creating a new object in the standard way (e.g., using the new keyword) is prohibitively expensive for a given application.
Implementation: Declare an abstract base class that specifies a pure virtual clone method. Any class that needs a "polymorphic constructor" capability derives itself from the abstract base class, and implements the clone operation.
Here the client code first invokes the factory method. This factory method, depending on the parameter, finds out the concrete class. On this concrete class, the clone method is called and the object is returned by the factory method.
* This is a sample implementation of Prototype method. We have the detailed description of all the components here.
** Record class, which is a pure virtual class that has a pure virtual method clone.
** CarRecord, BikeRecord and PersonRecord as concrete implementation of a Record class.
** An enum RecordType as one to one mapping of each concrete implementation of Record class.
** RecordFactory class that has a Factory method CreateRecord(…). This method requires an enum RecordType as parameter and depending on this parameter it returns the concrete implementation of Record class.
Another example:
To implement the pattern, declare an abstract base class that specifies a pure virtual clone member function. Any class that needs a "polymorphic constructor" capability derives itself from the abstract base class, and implements the clone operation.
The client, instead of writing code that invokes the new operator on a hard-wired class name, calls the clone member function on the prototype, calls a factory member function with a parameter designating the particular concrete derived class desired, or invokes the clone member function through some mechanism provided by another design pattern.
A client of one of the concrete monster classes only needs a reference (pointer) to a CPrototypeMonster class object to be able to call the ‘Clone’ function and create copies of that object. The function below demonstrates this concept:
Now originalMonster can be passed as a pointer to CGreenMonster, CPurpleMonster or CBellyMonster.

### Singleton

The Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. It is named after the singleton set, which is defined to be a set containing one element. This is useful when exactly one object is needed to coordinate actions across the system.
Check list
* Define a private static attribute in the "single instance" class.
* Define a public static accessor function in the class.
* Do "lazy initialization" (creation on first use) in the accessor function.
* Define all constructors to be protected or private.
* Clients may only use the accessor function to manipulate the Singleton.
Let's take a look at how a Singleton differs from other variable types.
Like a global variable, the Singleton exists outside of the scope of any functions. Traditional implementation uses a static member function of the Singleton class, which will create a single instance of the Singleton class on the first call, and forever return that instance. The following code example illustrates the elements of a C++ singleton class, that simply stores a single string.
Variations of Singletons:
Applications of Singleton Class:
One common use of the singleton design pattern is for application configurations. Configurations may need to be accessible globally, and future expansions to the application configurations may be needed. The subset C's closest alternative would be to create a single global struct. This had the lack of clarity as to where this object was instantiated, as well as not guaranteeing the existence of the object.
Take, for example, the situation of another developer using your singleton inside the constructor of their object. Then, yet another developer decides to create an instance of the second class in the global scope. If you had simply used a global variable, the order of linking would then matter. Since your global will be accessed, possibly before main begins executing, there is no definition as to whether the global is initialized, or the constructor of the second class is called first. This behavior can then change with slight modifications to other areas of code, which would change order of global code execution. Such an error can be very hard to debug. But, with use of the singleton, the first time the object is accessed, the object will also be created. You now have an object which will always exist, in relation to being used, and will never exist if never used.
A second common use of this class is in updating old code to work in a new architecture. Since developers may have used globals liberally, moving them into a single class and making it a singleton, can be an intermediary step to bring the program inline to stronger object oriented structure.
Another example: