Creational Patterns

Creational patterns defines the best possible way to initialize the object. These initialize the object according to the nature of the program. Creational design patterns abstract the instantiation process.They help make a system independent of how its objects are created,composed, and represented. Creational patterns become important as systems evolve to depend more on object composition than class inheritance.

There are 5 type of Creational Patterns

  • Factory pattern
  • Abstract Factory pattern
  • Singleton
  • Builder pattern
  • Prototype pattern

Factory Pattern

Factory pattern or Factory method pattern is a java class that is use to encapsulate object creation code. Suppose our super class has 'n' number of sub-classes and based on data provided, factory class return one of its sub-class object.

Example let's create an CourseFactory class that will return an Course object based on some data input.

View Source Code

Abstract Factory Pattern

Abstract factory pattern is one level higher than factory pattern. An abstract factory returns factories, and later on factory returns one of its sub-class based on data provided.

Example Suppose we need to get the various vehicle based on the vehicle type.

View Source Code

Singleton Pattern

Singleton pattern is one of the most important pattern used commonly. This pattern is used when we want to restrict class to make only single object and that single object is used by all other classes.

Example Suppose we have one singleton JDBC class that is this class will initialize only once and that object is shared by all other class/methods

View Source Code

Builder Pattern

Builder pattern is used to build complex object from simple objects. In other words, with the builder pattern, the same object construction process can be used to create different objects.
A Builder is an interface (or abstract class) that is implemented (or extended) by Concrete Builders.

Example Suppose we have different car components objects that combine to make complex car object.

View Source Code

Prototype Pattern

As a name suggest Prototype means making a clone that is a new object is created by cloning an existing one. The prototype pattern can be a useful way of creating copies of objects. If the cost of creating a new object is expensive and resource intensive, we prototype the object.

Example we can implement our own prototype pattern. So, we'll create a Prototype interface that features a doClone() method.

View Source Code