Reputation: 21
I am trying to understand a very commonly used pattern called 'Factory Method'. Why is it called 'Method'?
Also, what is the difference between the 'Abstract Factory' pattern and the 'Factory Method' pattern?
Upvotes: 1
Views: 643
Reputation: 27575
It's called "method" because the factory itself is some method of a class, usually a static method. For example, the class Monster
could have a method called Create
that would create some Monster or subtype of Monster.
If the class Monster
is abstract and has a factory method, then you could call it an Abstract Factory, because you can instantiate subtypes by calling its Factory Method.
The reason behind all this is that you delegate to the Factory the decision of which exact subtype should it return, depending on context or whatever.
Example in C#:
public abstract class Monster {
public static Monster Create() { // "Create" could have some parameters if needed.
return new CuteMonster(); // you could change this without having to change client code.
}
}
Upvotes: 3