Factory Design Pattern
The factory method is a design pattern that provides an interface or abstract class for creating an object and allows its subclasses to decide which class to be instantiated. Factory pattern is classified as a creational pattern.
When to use Factory Design 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.
Factory Design Pattern Implementation
OS.java Class
This is the parent interface of all the subclasses
Andriod.java, IOS.java, Windows.java Classes
All these three subclasses should implement same parent class
OSFactory.java Class
The return type of the factory method should be the parent class.
This Factory function is responsible for deciding which class should be instantiated. Based on the parameter we provided, this function will build and return an instance of the proper class.
FactoryMain.java Class
Output of the above code ;
Advantages
Factory design pattern provides approach to code for interface rather than implementation.
Factory pattern removes the body of actual implementation classes from client code. Factory pattern makes our code more robust, less coupled and easy to extend.
Factory pattern provides abstraction between implementation and client classes through inheritance.
Factory pattern removes the body of actual implementation classes from client code. Factory pattern makes our code more robust, less coupled and easy to extend.
Factory pattern provides abstraction between implementation and client classes through inheritance.







0 Comments