Creational Design Pattern - Factory Pattern
In my previous blog, I discussed the Abstract Factory Pattern, which you can read if you're interested. Today, I am going to discuss the Factory Pattern.
Factory Design Pattern
Factory design pattern is similar to abstract factory pattern and they both are creational design patterns. The only difference is that Factory pattern has only one factory class while abstract factory pattern can have multiple different factories which extend the main abstract factory class. So, if you want to implement an application that have multiple similar objects, you can use factory pattern. Otherwise, if you have to implement multiple different types of objects, you can use abstract factory pattern which allows you to create multiple factories.
For Factory design pattern, it is quite less complex than abstract one. Take a look at this following diagram. I used the same example for both abstract factory and factory pattern. So you can understand the difference between two of them easily.
The Factory Pattern may seem quite simple, if you are familiar with Abstract Factory pattern. It consists of 4 key components:
- User Interface where the main( ) method is written, allowing users interact with the software. It interacts with the factory by creating a factory object and different concrete objects such as Burger, Pizza, Taco and Ice cream can be created by using Factory object.
Factory factory = new factory();
factory.getItem("Burger");
factory.getItem("Pizza");
factory.getItem("Taco");
factory.getItem("Ice Cream");
- Factory serves as an mediator between the user interface and concrete classes. In this example, the factory class includes a method called getItem(), which accepts an input string as a parameter. Based on the provided input, the factory will create the corresponding object, such as a Burger, Pizza, Taco, or Ice Cream.
- Interface acts as a blueprint that multiple classes will implement. In this example, Food_Interface has get_food( ) method and this interface is implemented by multiple concrete classes.
- Concrete Classes will be implementing to an interface or otherwise, they will be extending to an abstract class.
Comments
Post a Comment