Creational Design Patterns
In the previous post, we saw the concept of Design pattern, classification of a design pattern as per their usage.
In this post, we will see what is creational design pattern and how to implement some of the creational design patterns in detail. At the end of the post, I will add GitHub link for a code reference
The creational design pattern provides object creation mechanisms that increase flexibility and reuse of existing code.
There are different Creational design patterns.
- Factory Method
- Abstract factory
- Builder
- Prototype
- Singleton
Out of these patterns, we will see Factory Method, Builder and Singleton creational design pattern.
1.Factory Method:
Factory Method 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.
In the Factory pattern, we create an object without exposing the creation logic to the client and the client uses the same common interface to create a new type of object.
The idea is to use a static member-function (static factory method) which creates & returns instances, hiding the details of class modules from the user.
Consider we have multiple implementations of an interface. For example, we have an interface named as OS with spec() method in it. There are three classes which implement OS interface named as Android OS, iOS, Windows OS and spec() defines which OS we are using.
Create a main class which will call each class.
public class MainClass {
public static void main(String[] args) {
OS osAndroid = new Android();
osAndroid.spec();
OS osIos = new Ios();
osIos.spec();
OS osWindows = new Windows();
osWindows.spec();
}
}
Problem with this approach:
Depends on requirements we will create an object of different classes and every time we have to provide an implementation. If we want to change OS from one to another every time we will have to compile and run the code. This will lead to exposing our code as well.
Solution:
To solve the above problem create a factory class called OperationSystemFactory. In the class create a method which accepts a string and returns the object of OS interface accordingly.
Now create an object of OperationSystemFactory class in our main class and call getInstance(with string parameter).
With this approach, we can call the instance of the required class at run time and no need to change the code, compile and run every time.
2. Builder pattern
Builder pattern aims to “Separate the construction of a complex object from its representation so that the same construction process can create different representations.” It is used to construct a complex object step by step and the final step will return the object. The process of constructing an object should be generic so that it can be used to create different representations of the same object.
Consider we are building a phone which has a configuration like ram size, processor, OS, screen size, battery, front camera, noOfSimCards. How will do?
Let’s create a class Phone.java. Define a variable for each the configuration. Create a parameterized constructor and pass all the variables as parameters. Call toString() method which returns all.
Create a new class Shop.java. In this class call constructor of Phone class. We have five variables which we are calling in constructor and print all the values.
Problem with this approach:
- One who is calling the constructor has to remember the correct sequence of variables. Currently, we have only 7 variables so that is not a problem but what if we have more than 50 variables. It is very difficult because we may send some wrong data through the constructor.
- Suppose we are building another phone which does not have a front camera. In that, we have to skip parameter value for variable frontCamera.But in this approach, we can not omit a parameter as it will throw a compile-time exception.
Solution:
To solve the above problem create one more class named PhoneBuilder who will be responsible to create a phone.
Take all variables into PhoneBuilder class. We will take setter methods for all variable. Instead of return type void make it as PhoneBuilder object. At runtime, we can specify which parameter we can set. Set return type as PhoneBuilder and return same.
We need to add one more method in PhoneBuilder class which takes all values of the parameter and build a phone for us. That method will return a new phone object. Let call that method getPhone().
Now In shop class, we will call an object of PhoneBuilder with only set methods for variables to set values along with getPhone(). It will set values only to those parameters which we passed the values and for other variables, it will take default value for example if the data type of variable for which we are not setting value is String, then by default, it will take null value for that variable.
Also, we can set value in any sequence so no need to remember the sequence.
2. Singleton pattern
Singleton is a creational design pattern that lets you ensure that a class has only one instance while providing a global access point to this instance.
Sometimes we need to have only one instance of our class, for example, a single DB connection shared by multiple objects as creating a separate DB connection for every object may be costly. Similarly, there can be a single configuration manager or error manager in an application that handles all problems instead of creating multiple managers.
How to implement it?
Create a Sample class and create a static instance of that class. Create a constructor of this class and make it private so that we can not create an instance with the default constructor. Then create a static method inside the sample class which returns the instance of a class/object.
Now create a new class called Singleton.java and call the static method in it. At any condition, we can create only one instance of Sample class. If we try to create an instance of Sample class using New keyword it will show the message “Sample has private access in Singleton. Sample”. The only way to create an instance is to call a static method present in Sample class which will return the same instance every time.
I am providing a GitHub link. You can download code from here.