Reputation: 3104
I see many people using something like this and call it Factory pattern.
class Factory {
public IProduct Create (ProductEnum type) {
switch (type) {
case ProductAType:
return new ProductA();
case ProductBType:
return new ProductB();
}
}
}
But isn't the real Factory pattern the one where you have one factory for each product type? So when you create new implementation of IProduct you have to create a new factory class and redefine the Create method. Something like in this picture:
Is the first example also Factory pattern or it is something else, and should that be used or not?
Upvotes: 2
Views: 1147
Reputation: 17066
But isn't the real Factory pattern the one where you have one factory for each product type?
If by, "real Factory pattern" you mean the GoF Factory Method pattern, then yes: the GoF pattern states that, "subclasses decide which class to instantiate."
Is the first example also Factory pattern or it is something else,
The first example is not a GoF pattern, but it is commonly used and commonly referred to as a Factory. You may also see it called a Simple Factory, or if the method is static, a Static Factory, to differentiate it from the GoF. Confusion is rampant when the distinction is not made between GoF patterns and related (but unofficial) coding idioms.
and should that be used or not?
The reason you would not see an idiom like this in the GoF patterns is that it violates the open/closed principle. The same factory class must be modified every time a new product is added, rather than adding products via inheritance & polymorphism per the GoF. You must judge for yourself whether the simplicity of violating the open/closed principle outweighs potential maintainability.
Upvotes: 1
Reputation: 12616
There are actually two factory patterns. The first one is called factory method and the second one displayed in the picture is abstract factory. People talking about a factory pattern usually don't know one of them or don't understand the difference. It would be waste of time to describe the difference here so I'll point you to this SO question to get started. There's obviously much more on the internet.
What you have there in the code snippet is factory method.
Upvotes: 1