本文介绍了为什么抽象工厂处理家族和工厂方法生成单个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从我所看到的,抽象工厂模式通常关注自己创建几个与同一个系列相关联的对象,而工厂方法模式也涉及生成单个对象。



考虑以下示例,它会翻转这些问题:

  //工厂方法(基类)允许用于创建对象的家族
public class BasePizzaCreator {
abstract ISauce CreateSauce();
abstract IToppings CreateToppings();
抽象ICrust CreateCrust();
}

//抽象工厂(界面)定义合同创建一个对象
public interface IPizzaFactory {
abstract IPizza CreatePizza();
}

很明显,您可以使用它们方式 - 但它是否违反了模式的精神?如果是这样,为什么?



我真正想要了解的是:为什么抽象工厂是创建相关对象系列的更好方法,而Factory方法更好的方法创建单个对象?

解决方案

在给定的示例中, BasePizzaCreator 是一个抽象工厂,但 IPizzaFactory 不是任何GoF设计模式(尽管它有时被称为简单工厂)。


$ b $关于为什么Abstract Factory处理产品系列的原因,而Factory Method处理单个产品:这仅仅是GoF定义的产品。随着GoF书的提及,实现抽象工厂的最常用方法是使用多种工厂方法。从客户的角度来看,抽象工厂可能是优选的,因为客户端通过组合/委托来调用它,而不是Factory Method,需要客户端继承该方法。



最后,注意抽象工厂与工厂方法是Stack Overflow中第二大流行的设计模式主题。不幸的是,有很多(高度高调的)错误信息也被发布,所以当有疑问时,总是回到这本书。









From what I have read, the abstract factory pattern typically concerns itself with creating several objects which are all associated with the same family, and the factory method pattern concerns itself with generating a single object.

Consider the following example, which flips those concerns:

// Factory Method (base class) allowing for creation of families of objects
public class BasePizzaCreator{
    abstract ISauce CreateSauce();
    abstract IToppings CreateToppings();
    abstract ICrust CreateCrust();
}

// Abstract Factory (interface) defining contract to create a single object
public interface IPizzaFactory{
    abstract IPizza CreatePizza();
}

It is obvious that you can use them this way - but is it a violation of the spirit of the patterns? If so, why?

What I really want to understand here is this: Why is Abstract Factory the better approach for creating families of related objects, and Factory method the better approach to creating a single object?

解决方案

In the given examples, BasePizzaCreator is an Abstract Factory, but IPizzaFactory is not any GoF design pattern (though it is sometimes referred to as a Simple Factory).

As to why Abstract Factory deals with product families while Factory Method deals with a single product: that's simply how the GoF defined them. As the GoF book mentions, the most common way to implement an Abstract Factory is with multiple Factory Methods. From a client's perspective, Abstract Factory may be preferable because clients invoke it through composition/delegation, as opposed to Factory Method which requires clients to inherit that method.

Finally, note that "Abstract Factory vs. Factory Method" is the second-most popular design patterns topic on Stack Overflow. Unfortunately, there is a lot of (highly-upvoted) misinformation posted as well, so when in doubt, always refer back to the book.

这篇关于为什么抽象工厂处理家族和工厂方法生成单个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 20:39