Monday, November 21, 2011

Factory Method Creational Design Pattern


Factory Method is most commonly used creational design pattern. It provides an abstraction or an interface and lets subclass or implementing classes decide which class or method should be instantiated or called, based on the conditions or parameters given.


Implementation:

Shape:
public interface Shape {
      public void draw();    
}
Circle:
public class Circle implements Shape {
      private double radius = 0;
     
      public Circle(double radius){
            this.radius = radius;
      }
     
      public void draw(){
            System.out.println("Hi! This is circle");
            System.out.println("Circle radius : " + radius );
      }    
}
Square:
public class Square implements Shape{
      private double side = 0;
     
      public Square(double side){
            this.side = side;
      }
     
      public void draw(){
            System.out.println("Hi! This is square");
            System.out.println("Square side : " + side);
      }
}
Rectangle:
public class Rectangle implements Shape {
      private double length = 0;
      private double breadth = 0;
     
      public Rectangle(double length, double breadth){
            this.length = length;
            this.breadth = breadth;
      }
     
      public void draw(){
            System.out.println("Hi! This is rectangle");
            System.out.println("Rectangle length : " + length);
            System.out.println("Rectangle breadth : " + breadth);
      }    
}
ShapeFactory:
public class ShapeFactory {
      public Shape createCircle(double radius){
            return new Circle(radius);
      }
     
      public Shape createSquare(double side){
            return new Square(side);
      }
     
      public Shape createRectangle(double length, double breadth){
            return new Rectangle(length, breadth);
      }
}
User:
public class User {
      public static void main(String[] args) {
            ShapeFactory factory = new ShapeFactory();
            Shape shape = null;
            shape = factory.createCircle(1.23);
            shape.draw();
            shape = factory.createSquare(23);
            shape.draw();
            shape = factory.createRectangle(23, 25);
            shape.draw();    
      }
}


No comments:

Post a Comment