I have a class called GatewayAPI, which has to load configs from a file, when used. I first wanted to put the get_config() method in the constructor, but I don't like this design for testing purposes.

Now I plan to do a factory, which creates this GatewayObject. Is this a typical usecase for the Factory Pattern?

Second question: Is it enough to put a method called "create" in the APIGateway class or should the factory be independent?

enter image description here

1 Answer 1

  1. Yes this is a typical use case for the Factory pattern.

The point of a factory is to apply some set of complex logic to create and configure an object/object ecosystem for use, possibly accepting some parameters to refine/control that logic.

  1. Singletons in code are generally a bad idea.

A class level method is a singleton. Later when you want two different pieces of factory logic, you can't because only one piece of factory logic is called class::create().

This makes any sort of testing, particularly Unit Testing painful, as you cannot easily Mock the factory, or the returned object.

If this create() was an object level method instead, it is still a problem. The GatewayAPI objects now have conflicting roles. Is the object a gateway, or a factory to get a gateway? When you call create() and get an object back, is that the gateway, or a factory to get the gateway? How many turtles deep does this go?

  1. Bonus round. The configuration for the GatewayAPI should be separate from the GatewayAPI.

As the factory is responsible for configuring the GatewayAPI, the GatewayAPI should no longer be responsible for knowing what that configuration is, before it is configured.

It is the factory's job now to know what the configuration is/how to obtain the configuration/be told the configuration and then apply it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.