Here are two ways to instantiate an object:
Option 1:
Thing thing = new Thing();
Option 2: (the factory is a Static Factory, but it could also be a Simple Factory).
Thing thing = ThingFactory.createThing();
Where:
class ThingFactory(){
public static Thing createThing(){
return new Thing();
}
}
Option 2 is said to be better, because using a factory decouples the client code from the concrete implementation of the class it's instantiating.
However what difference does it actually make if I use new Thing()
or factory.createThing()
? The only difference between the two options is that the instantiation code is moved to a different place.
As I explained above I know the 'academic' explanation to why using a factory is 'better', but I don't actually see the practical benefit. In both cases, the client knows exactly what it wants: a Thing
. The only difference is the exact line of code: new Thing()
or factory.createThing()
.
More sophisticated factories, I can see their benefit. For example using the Abstract Factory pattern, I could create different Factory
subclasses that instantiate different concrete implementations of Thing
, and inject the suitable Factory
to the client at runtime, without the client worrying about the concrete implementation it receives. BlueThingFactory
instantiates BlueThing
, RedThingFactory
instantiates RedThing
, but the client only cares that it receives a Thing
.
This is with more sophisticated factories.
But I'm unable to see the benefit of using a simple factory as in the example I described. All it does is move new Thing()
to a different place. I don't understand the benefit of this.
Please explain to me the actual benefits of using a simple factory.
static
factory in favor of an injected one. Factories allow instantiation to use caches if the language doesn't support it natively. It'd also allow for parameter checking without starting object instantiation. Some stuff might be language dependent...new Integer(42)
vsInteger.valueOf(42)
and consider that simple factory.