Understanding the Factory Design Pattern in Java

06 May 2023 Balmiki Mandal 0 Core Java

The Factory Design Pattern in Java

The Factory Design Pattern is a creational design pattern that allows for the creation of objects without needing to specify the exact class of the object that will be created. The Factory pattern provides an interface for creating objects, and then relies on subclasses to define which object should be created. This pattern is very useful for code that needs to work with objects from different classes that share a common interface or base class.

In Java, the Factory pattern is used to create collections of objects or instances of classes. It can also be used to create objects whose class type is not known until runtime. The Factory pattern is also beneficial when dealing with complex objects that have lots of dependencies and require nontrivial construction or setup.

The Factory pattern works by defining an interface which declares methods used to create objects. The concrete classes that implement this interface are responsible for providing an implementation of the methods defined by the interface. The client code is given the responsibility of deciding which concrete class to use based on some criteria.

Here is an example of how the Factory pattern can be used in Java:

public interface ShapeFactory {
   public Shape createShape(String shapeType);
}
 
public class TriangleFactory implements ShapeFactory {
   @Override
   public Shape createShape(String shapeType) {
      if (shapeType.equalsIgnoreCase("Triangle")) {
         return new Triangle();
      }
 
      return null;
   }
}
 
public class CircleFactory implements ShapeFactory {
   @Override
   public Shape createShape(String shapeType) {
      if (shapeType.equalsIgnoreCase("Circle")) {
         return new Circle();
      }
 
      return null;
   }
}

The client code decides which concrete class to instantiate and call its createShape() method like this:

ShapeFactory factory = new TriangleFactory();
Shape shape = factory.createShape("Triangle");
// ...
factory = new CircleFactory();
shape = factory.createShape("Circle");

The Factory pattern is very useful when dealing with large applications that require complex or multiple objects to be created. It makes the code easier to read and understand, and also encourages good coding practices such as loose coupling and separation of concerns.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.