Creational patterns provide a way to create objects while hiding the creation logic, rather than instantiating objects directly using new operator. This gives program more flexibility in deciding which objects need to be created for a given use case.
Factory Method Pattern
With factory pattern, objects are created without exposing the creation logic to the client. It refers to the factory method that encapsulates the creation of objects such that factory method can be override in a subclass.
Abstract factory pattern works around a super factory which creates other factories. This factory is also called the factory of factories.
The method createButton on the GuiFactory interface returns objects of type Button. What implementation of Button is returned depends on which implementation of GuiFactory is handling the method call.
//Concrete Factory classWinFactoryimplementsGUIFactory{ public Button createButton(){ returnnew WinButton(); }
public Label createLabel(){ returnnew WinLabel(); } }
//Concrete Factory classOSXFactoryimplementsGUIFactory{ public Button createButton(){ returnnew OSXButton(); }
public Label createLabel(){ returnnew OSXLabel(); }
}
//Concrete Product classOSXButtonimplementsButton{ publicvoidpaint(){ System.out.println("I'm an OSXButton"); } }
//Concrete Product classWinButtonimplementsButton{ publicvoidpaint(){ System.out.println("I'm a WinButton"); } }
//Concrete Product classOSXLabelimplementsLabel{ publicvoidpaint(){ System.out.println("I'm an OSXLabel"); } }
//Concrete Product classWinLabelimplementsLabel{ publicvoidpaint(){ System.out.println("I'm a WinLabel"); } }
//Client application is not aware about the how the product is created. Its only responsible to give a name of //concrete factory classApplication{ publicApplication(GUIFactory factory){ Button button = factory.createButton(); Label label = factory.createLabel(); button.paint(); label.paint(); } }
publicclassApplicationRunner{ publicstaticvoidmain(String[] args){ new Application(createOsSpecificFactory()); }
Singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.
The Abstract Factory, Builder, and Prototype patterns can use Singletons in their implementation.
Facade objects are often singletons because only one Facade object is required.
State objects are often singletons.
Singletons are often preferred to global variables because:
They do not pollute the global namespace (or, in languages with namespaces, their containing namespace) with unnecessary variables.
They permit lazy allocation and initialization, whereas global variables in many languages will always consume resources.
classSingleton{ privateSingleton(){} privatestaticclassHolder{ privatestaticfinal Singleton instance = new Singleton(); } public Singleton getInstance(){ return Holder.instance; } }
Prototype Pattern
Prototype pattern is used when creation of object directly is costly. For example, an object is to be created after a costly database operation. We can cache the object, returns its clone on next request and update the database when needed thus reducing database calls.
The mitotic division of a cell — resulting in two identical cells — is an example of a prototype that plays an active role in copying itself and thus, demonstrates the Prototype pattern. When a cell splits, two cells of identical genotype result. In other words, the cell clones itself.
publicclassConcretePrototype1extendsPrototype{ @Override public Prototype clone(){ returnsuper.clone(); } }
publicclassConcretePrototype2extendsPrototype{ @Override public Prototype clone(){ returnsuper.clone(); } }
Builder Pattern
Instead of using numerous constructors, the builder pattern uses another object, a builder, that receives each initialization parameter step by step and then returns the resulting constructed object at once.
Builder often builds a composition object. Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed. Sometimes creational patterns are complementary: Builder can use one of the other patterns to implement which components are built.
publicclassStreetMap{ privatefinal Point origin; privatefinal Point destination;
privatefinal Color waterColor; privatefinal Color landColor; privatefinal Color highTrafficColor; privatefinal Color mediumTrafficColor; privatefinal Color lowTrafficColor;
publicstaticclassBuilder{ // Required parameters privatefinal Point origin; privatefinal Point destination;
// Optional parameters - initialize with default values private Color waterColor = Color.BLUE; private Color landColor = new Color(30, 30, 30); private Color highTrafficColor = Color.RED; private Color mediumTrafficColor = Color.YELLOW; private Color lowTrafficColor = Color.GREEN;