Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
539 views
in Technique[技术] by (71.8m points)

design patterns - Why does Abstract Factory deal with families, and Factory Method with generating a single object?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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. The GoF book mentions the most common way to implement an Abstract Factory is with multiple Factory Methods; but I've not seen that in practice. 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...