1

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?

Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
skemnaik
  • 21
  • 2
  • 1
    http://stackoverflow.com/questions/5739611/differences-between-abstract-factory-pattern-and-factory-method and http://stackoverflow.com/questions/1001767/what-is-the-basic-difference-between-factory-and-abstract-factory-patterns ? – Soner Gönül Apr 10 '15 at 13:12
  • @SonerGönül do you know why it is called Method ? – skemnaik Apr 10 '15 at 13:15

1 Answers1

3

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.
    }
}
heltonbiker
  • 26,657
  • 28
  • 137
  • 252
  • While I agree, and upvote, your answer regarding the Factory Method, I don't agree with your answer regarding the Abstract Factory. 'The essence of the Abstract Factory Pattern is to "Provide an interface for creating families of related or dependent objects without specifying their concrete classes.' My understanding is that the 'abstract' part of Abstract Factory is related to the factory not the product. – David Osborne Apr 10 '15 at 13:22
  • @DavidOsborne I think we're talking about the same thing. Look at the sample code I added: the factory is abstract, the method is not, and the decision client code doesn't specify the subclass (it doesn't even can), because this decision is encapsulated by the Abstract Factory class. Note that I didn't called the class `MonsterFactory`, but that would be a valid choice I think. – heltonbiker Apr 10 '15 at 13:26