Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
538 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...