To implement standard patterns of object creation

Theory

Creational Patterns provide object creation mechanisms that increase flexibility and reuse of existing code. Everyone knows that new Keyword is used to create an object. Sometimes, the nature of the object must be changed according to the nature of the program. In such cases, we must get the help of creational design patterns to provide more general and flexible approach.

Consider the following creational patterns:

  • Factory: is a creational design pattern that provides an interface for creating objects in a superclass but allows subclasses to alter the type of objects that will be created.

  • Need for Factory pattern:

    • When a class doesn't know what sub-classes will be required to create

    • When a class wants that its sub-classes specify the objects to be created.

    • When the parent classes choose the creation of objects to its sub-classes.

    It promotes the loose-coupling by eliminating the need to bind application-specific classes into the code.

    Say you have a class hierarchy of the form:

    8-1

    Now creating objects of the through a factory class as follows:

    8-2

    The demo class can be inserted to instantiate the different shapes:

    8-3

    The class Shape, Circle and Square are designed as follows:

    8-4

    8-5

    8-6

    8-7

    The class ShapeFactory and ShapeDemo are designed as follows:

    8-8

    8-9

  • Singleton: This pattern makes sure that there is only one instance of object created at any point.

  • Singleton Shape class provides a static method to get its static instance to outside world.

    8-10

    8-11

  • Builder: A Builder class builds the final object step by step. This builder is independent of other objects.

  • 8-12

    8-13

    8-14

    8-15

    8-16

    8-17

    8-18