简体   繁体   English

“工厂方法”设计模式

[英]“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. 例如, Monster类可以有一个名为Create的方法,它可以创建一些Monster或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. 如果类Monster是抽象的并且有一个工厂方法,那么你可以将它称为抽象工厂,因为你可以通过调用它的工厂方法来实例化子类型。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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