Wednesday 6 August 2014

Factory Pattern

I'm going to go over the Factory design pattern in Java. The factory design pattern is probably the most commonly used design pattern,
it lets the user create objects without using the 'new' operator. This gives the program more flexibility in deciding which objects need to be created for a given use case.

The design pattern comes under the category of Creational Patterns. A creational pattern is a pattern which creates objects while hiding the logic. The below image is a UML of what we are going to create.

Taken from http://www.tutorialspoint.com/


So I've taken this image from a tutorial website which is why it's using shapes as it's data. I'll do the same

First off we are going to create our interface. Our interface will have a draw method, this tells all classes who implement this interface that they need a draw method.

public interface Shape {
    void draw();
}

Then we need to create three shape classes which will implement the Shape interface, and thus overriding the draw method with their own implementation.

public class Square implements Shape {
  @Override
  public void draw() {
       System.out.println("Square");
  }
}

public class Triangle implements Shape {
  @Override
  public void draw() {
       System.out.println("Triangle");
  }
}

public class Circle implements Shape {
  @Override
  public void draw() {
       System.out.println("Circle");
  }

}

Now we need to create the ShapeFactory class. In this class we will create a method which returns a Shape object. As Triangle, Square and Circle all implement Shape they are now classed as Shape Objects. The method will have a parameter named 'type' which will decided which shape to create.

public class ShapeFactory {
    public Shape getShape(String type){
        if(type == "SQUARE")
              return new Square();
        if(type == "CIRCLE")
              return new Circle();
        if(type == "TRIANGLE")
              return new Triangle();
        return null;
    }
}


Now we need to a class to call this method. Lets create our FactoryPatternDemo class. Within this class we will have a main method which will call our ShapeFactory.getShape method and pass in a string value of the shape we wish to create. Calling the Shapes draw method will return the draw method of that Shape.

public class FactoryPattern {
    public static void main(String[] args){
        ShapeFactory factory = new ShapeFactory();
        Shape square = factory.getShape("SQUARE");
        square.draw();
        Shape circle = factory.getShape("CIRCLE");
        circle.draw();
        Shape triangle = factory.getShape("TRIANGLE");
        circle.draw();
   }
}


And that's pretty much it, when we run this program we should see and output like the following

Square
Circle
Triangle

This proves that each of these objects have been created. Pretty cool!

No comments:

Post a Comment