I understand that one of the main advantages of the Factory Method over Simple Factory is that it doesn't violate the Open-Closed SOLID Principle. That is, the former doesn't require modifying the switch statement when new types are added.
There is one piece on which I am hoping to get clarification. If I were to use a simple factory, I would have a factory like this (simplified):
public class ObjectFactory {
public static IObject CreateObject(ObjectTypeEnum objectType) {
switch (objectType) {
case TypeA:
return ObjectA;
break;
case TypeB:
return ObjectB;
break;
case TypeC:
return ObjectC;
break;
}
}
}
and the client would call it like this:
IObject myObject = ObjectFactory.CreateObject(objectType);
The disadvantage in the literature is that CreateObject will need to be modified when new object types are added.
But with the Factory Method, wouldn't we just be moving this modification from the factory to the client, like this (client code):
IObject myObject;
switch (objectType) {
case TypeA:
myObject = ObjectAFactory.CreateObject();
break;
case TypeB:
myObject = ObjectBFactory.CreateObject();
break;
case TypeC:
myObject = ObjectCFactory.CreateObject();
break;
}
In this case the client will need to be modified each time a new type is added, versus in the previous case the factory would need to be modified. So what is the advantage then of one over the other? Please don't mark this as duplicate, I have looked at many SO posts about factories and none address this specific distinction.
Is there a better solution that doesn't violate the Open/Closed Principle on either the client or factory side?
factory method
pattern still violate the open-closed principle if still use theswitch
statement. In other words, we still need to modify the code. – Woman