Factory Method
Intent/Purpose Factory Method is used to deal with a problem of creating objects without specifying the EXACT class of object that we will be creating or explicitly calling the object’s constructor. As a result, we get less code repetition and a higher degree of abstraction This can be useful when a class cant anticipate the type of object it must create.
Definition/Description A factory method is a creational pattern Its purpose is to define an interface for creating objects which allows a class to defer instantiation to a subclass Factory method is another, more abstract and elegant way of creating object with the same base class without using their constructor “Multi-SubClass Constructor”
Terminology Product - usually an abstract type of object that a factory method will create Concrete Product – a concrete instance of Product Creator - abstract type/interface which returns an object of type Product. Concrete Creator – overrides the factory method in Creator
UML
Advantages Reduce code verbosity Have clear distinguishable name for the Factory Method unlike constructors Not required to create a new object when called, this adds to flexibility
Disadvantages Code can become more confusing
REFERENCES Design Patterns by Gang of Four Wikipedia Stack Overflow