Monday, 26 June 2017

Software Engineering: Factory Method Pattern

Creational Pattern - Strategy Pattern


Intent
Define an interface for creating an object, but let sub classes decide which class to instantiate. Factory Method lets a class defer instantiation to sub classes.

Why is this used?
This is useful for when you only have one concrete creator, because you are decoupling the implementation of the sub class from its use.

If you add additional sub class or change a sub classes implementation, this will not affect the Creator. As the Creator is not tightly coupled with the sub classes.


UML diagram representation

https://www.tutorialspoint.com/design_pattern/images/factory_pattern_uml_diagram.jpg

Source code example
public class FactoryPatternDemo {

   public static void main(String[] args) {
      ShapeFactory shapeFactory = new ShapeFactory();

      //get an object of Circle and call its draw method.
      Shape shape1 = shapeFactory.getShape("CIRCLE");

      //call draw method of Circle
      shape1.draw();

      //get an object of Rectangle and call its draw method.
      Shape shape2 = shapeFactory.getShape("RECTANGLE");

      //call draw method of Rectangle
      shape2.draw();

      //get an object of Square and call its draw method.
      Shape shape3 = shapeFactory.getShape("SQUARE");

      //call draw method of circle
      shape3.draw();
   }
}
https://www.tutorialspoint.com/design_pattern/factory_pattern.htm

More to follow...

No comments:

Post a Comment

Software Engineering: Bad Smells! (Smelly code)

Bad Smells! What are bad smells? This refers to any symptom in the source code of a program that possibly indicates a deeper problem.  ...