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