Skip to content
Advertisement

How to create a self registering factory in Java?

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: http://www.jkfill.com/2010/12/29/self-registering-factories-in-c-sharp/. 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;
      }     
      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;
   }
}

Advertisement

Answer

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.
Advertisement