- 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.
- 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
This makes any sort of testing, particularly Unit Testing painful, as you cannot easily Mock the factory, or the returned object.
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?
- Bonus round. The configuration for the
GatewayAPI should be separate from the
As the factory is responsible for configuring 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.