Java factory design pattern

Java factory design pattern is one of the most used design pattern. It comes under the Creational Design Pattern category.

In factory design pattern we create an object from a factory class without exposing the creation logic to the client. Objects will be created by an interface or abstract class. The type of the object will be one of the subclasses and it will depends upon the input which we pass to the factory.

Main advantage of factory design pattern is it provides the loose-coupling.

Let’s look at the factory design pattern with below example. We are taking here an example of different shapes like Circle, Rectangle and Square. We will create an interface (Shape) and sub classes will implement this Shape interface. We will create ShapeFactory to get the different shape type objects. We will pass the shape type to ShapeFactory to get that type of object.

Example

Shape.java

package com.w3spoint;
 
public interface Shape {
	void drawShape();
}

Circle.java

package com.w3spoint;
 
public class Circle implements Shape {
	@Override
	public void drawShape() {
		System.out.println("Shape Circle.");
	}
}

Rectangle.java

package com.w3spoint;
 
public class Rectangle implements Shape {
	@Override
	public void drawShape() {
		System.out.println("Shape Rectangle.");
	}
}

Square.java

package com.w3spoint;
 
public class Square implements Shape {
	@Override
	public void drawShape() {
		System.out.println("Shape Square.");
	}
}

ShapeFactory.java

package com.w3spoint;
 
public class ShapeFactory {
   //getShape method returns object of input type shape
   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("Square")){
         return new Square();
      }
 
      return null;
   }
}

FactoryPatternTest.java

package com.w3spoint;
 
 
public class FactoryPatternTest {
	public static void main(String args[]){
		ShapeFactory shapeFactory = new ShapeFactory();
 
	      //Get Circle class object
	      Shape shape1 = shapeFactory.getShape("Circle");
 
	      //call drawShape method of Circle
	      shape1.drawShape();
 
	      //Get Rectangle class object
	      Shape shape2 = shapeFactory.getShape("Rectangle");
 
	      //call drawShape method of Rectangle
	      shape2.drawShape();
 
	      //Get Square class object
	      Shape shape3 = shapeFactory.getShape("Square");
 
	      //call drawShape method of Square
	      shape3.drawShape();
	}
}

Output

Shape Circle.
Shape Rectangle.
Shape Square.
Content Protection by DMCA.com
Please Share