Factory Design Pattern
Factory design pattern is a creational design pattern. In Factory design pattern we create a factory method which gives us object on the basis of the input we provide. Objects are being created without exposing the creation logic of instance from client. Factory design pattern is mainly used when we have one super class and multiple sub class and on the basis of the input we have to return one of the sub class. Super class in design pattern can be an abstract class, interface and normal class.
In below diagram, we have interface as Computer, we have implemented it as "PC" in which we need normal RAM, CPU and Hard Disk and other we have implemented it as "Server" in which we have High RAM, High CPU and very large memory Hard Disk. Client class will ask to factory method to give the instance of one of them and factory method will return the instance of PC or Server on the basis of input.
Implementation :
Computer.java
Computer.java
PC.java :
Server.java
ComputerEnum.java
ComputerFactory.java
Client.java
How factory design pattern is useful ?
Factory design pattern helps in decoupling the code , As you can see in above Client class does not need to create object of PC and Server explicitly. Factory method is responsible to create objects only. Client class does not need to worry about creation logic of Computers it has to just ask to Factory method to give and focus on business logic it wants to do.
"If we wont have used factory design pattern and created the PC and Server object inside client class only then in that case there would be lot of if else condition which also break Single Responsibility Behavior of SOLID design principle. Since now Client class responsibility is not just to handle the business logic but to create the Computers object as well."
Real life example of Factory Design Pattern
We can relate our factory design code example with real life example of Factory which produces all types of computer as PC, Server etc. We can think of Client class as some Computer Showroom where all types of computers are sell to the customer. Now if a customer comes to the showroom(Client class) and wish to buy PC . Showroom (Client class) does not need to worry about creation and packing of PC, it just give order to factory and factory in return provide the PC on demand.
It covers our main concepts regarding the factory design pattern, if you have any questions and doubts please comment.
Comments
Post a Comment