How to create a self registering factory in Java?

Tags: , ,

Factory pattern violates the OCP principle because it uses if() statements, which implies that if any class is added then the factory class has to change, being against SOLID principles. Self registering classes are supposed to address this problem according to this resource: The problem is that i don’t know C#. Can someone make an example of this in Java? Thanks in advance.

public class ShapeFactory {

   //The purpose of self registering classes is to avoid if's
   public Shape getShape(String shapeType){
      if(shapeType == null){ //Get rid of this
         return null;
         return new Circle();

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

      } else if(shapeType.equalsIgnoreCase("SQUARE")){
         return new Square();

      return null;


That self-registering thing is a bad idea. Eventually, it will be extremely difficult to know which factories are actually registered, and what their names are, and which name strings are thereby supported.

It’s better, and easy, to keep things straightforward. Usually, it would be something like:

  • ShapeFactory should have a Map<String, Supplier<Shape>> that maps shape type strings to the corresponding factories; and
  • ShapeFactory, or a builder for it, should have an addShapeType(String,Supplier<Shape>) that is used to register all the types while creating a ShapeFactory instance.

Source: stackoverflow