简体   繁体   中英

“Factory Method” Design Pattern

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?

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.
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM