What is Factory Design Pattern ?

The Factory Design Pattern comes under creational design patterns. The factory pattern allows a single factory to provide multiple instances of one object. Purpose of the factory pattern is to provide all the objects from one single factory. This is analogous to the way a factory works. A factory will produce multiple copies of Products/Objects. Using Factory Design Pattern will provide proper structure to the code, and is easy to maintain.

To implement a factory design pattern we need to follow following steps

1. Create an interface of the object we want to return.
2. Create concreate class implementing these interfaces.
3. Create a factory class which will return these objects.

  1. public interface Shape{
  2. public void draw();
  3. }
  5. public class Circle implements Shape{
  6. @override
  7. public void draw()}{
  8. System.out.println("Draw for circle")
  9. }
  10. }
  12. public class Square implements Shape{
  13. @override
  14. public void draw()}{
  15. System.out.println("Draw for square")
  16. }
  17. }
  19. public class MyFactory{
  20. publoc MyFactory(){}
  21. public Shape getShape(String obj){
  22. if(obj.equals("CIRCLE")){
  23. return new Circle();
  24. }
  25. if(obj.equals("SQUARE")){
  26. return new Square();
  27. }
  28. return null;
  29. }
  30. }
  32. class MainClass{
  33. public static void main(String[] args){
  34. Shape s1 = null;
  35. Shape s2 = null;
  36. MyFactory shapeFactory = new MyFactory();
  37. s1 = shapeFactory("CIRCLE");
  38. s2 = shapeFactory("SQUARE");
  39. s1.draw();
  40. s2.draw();
  41. }
  42. }

In the above example we have created a interface called Shape. Also we have created 2 classes implementing Shape interface namely Circle and Square. The Factory class MyFactory accepts the type of object required and dynamically creates them and returns them.

Practical Usage Of Factory Design Pattern

The Factory design pattern is very useful in creating multiple objects which inherit a same parent. For example in a bank employee and customer . Both of them are human beings. Hence HumanFactory class can be defined which return both employee and customers.

Alternate practical use is, consider a VechicleFactory which returns various vehicles like, car,bike etc. All vehicles will inherit properties of the parent vehicle class.


Please enter your comment!
Please enter your name here