Factory Design Patterns

Factory design pattern is creational design pattern , this design pattern is used whenever developer does not need to expose the object creational logic. In factory pattern objects are created using the factory class. This class will be having the object creation part. So when ever the new object is needed of specific type we can create the object using the factory class. Below diagram shows the basic structure of factory pattern.



One of the example where we can use this design pattern is in a case some predefined parameters are there for creating object. So what we can do in our case is , we can pass the type of object in getShape() method and based on the type with default attributes we can return the required object.


Let's see some practical example of it.

Shape Class

package com.design.pattern.factory;

public interface Shape {
	void draw();
}

Circle Class

package com.design.pattern.factory;

public class Circle implements Shape {

	@Override
	public void draw() {
		System.out.println("Drawing circle...");
	}

}

  

Triangle Class

package com.design.pattern.factory;

public class Triangle implements Shape {

	@Override
	public void draw() {
		System.out.println("Drawing triangle...");
	}

}
  

Rectangle Class

package com.design.pattern.factory;

public class Rectangle  implements Shape {

	@Override
	public void draw() {
		System.out.println("Drawing rectangle...");
	}

}

ShapeFactory Class

package com.design.pattern.factory;

public class ShapeFactory {

	public static final String CIRCLE="circle";
	public static final String TRIANGLE="triangle";
	public static final String RECTANGLE="rectangle";
	
	public Shape getShape(String shapeType) {
		if (shapeType == null) {
			return null;
		}
		if (shapeType.equalsIgnoreCase(CIRCLE)) {
			return new Circle();

		} else if (shapeType.equalsIgnoreCase(RECTANGLE)) {
			return new Rectangle();

		} else if (shapeType.equalsIgnoreCase(TRIANGLE)) {
			return new Triangle();
		}

		return null;
	}

}


FactoryDemo Class

package com.design.pattern.factory;

public class FactoryDemo {

	public static void main(String[] args) {

		ShapeFactory shapeFactory = new ShapeFactory();

		Shape shape1 = shapeFactory.getShape(ShapeFactory.CIRCLE);
		Shape shape2 = shapeFactory.getShape(ShapeFactory.TRIANGLE);
		Shape shape3 = shapeFactory.getShape(ShapeFactory.RECTANGLE);
		shape1.draw();
		shape2.draw();
		shape3.draw();

	}
}





No comments:

Post a Comment