Skip to content
Advertisement

Correct Use Of Factory Pattern?

I have been doing research on the factory design pattern and was wondering if the below example, while not “textbook” is technically a correct use of it. Is there another design pattern that may fit the situation better?

public class MySimpleObjectFactory {

    private SomeTransformer someTransformer;

    public MySimpleObjectFactory(SomeTransformer someTransformer){
       this.someTransformer = someTransformer;
    }

    public SimpleObject getSimpleObject(SomeObject someObject){
            PropA propA = someTransformer.transform(someObject);      
            return SimpleObject.builder()
                  .propA(propA)
                  .build();
    }


    public SimpleObject getSimpleObject(SomeObject someObject, AnotherObject anotherObject){
            PropA propA = someTransformer.transform(someObject, anotherObject);      
            return SimpleObject.builder()
                  .propA(propA)
                  .build();
    }

    public SimpleObject getSimpleObject(SomeObject someObject, AnotherObject anotherObject, YetAnotherObject yetAnotherObject){
            PropA propA = someTransformer.transform(someObject, anotherObject, yetAnotherObject);      
            return SimpleObject.builder()
                  .propA(propA)
                  .build();
    }

}

Advertisement

Answer

IMO: Looks like the given code example actually implemented the Factory Method pattern with using the Method Object solution https://refactoring.guru/replace-method-with-method-object.

Because for the client code, it will look like one method that can build different objects based on the parameters.

The Factory pattern solve specific kind of problem (when you need to build different groups of objects based on some condition), you can see more information here https://refactoring.guru/design-patterns/abstract-factory

Advertisement