Why are there two separate patterns: Abstract Factory and Factory Method
The factory method is fixed - you cannot change it at runtime.
The factory annotation allows you to create objects with a different factory that can be selected at runtime, depending on some criteria.
Button button = WinButtonFactory.create(); //will always be a "windows button"
Button button = buttonFactory.create();
on the second, how can it be WinButtonFactory extends ButtonFactory
or MacOSXButtonFactory extends ButtonFactory
. You can transfer one or the other depending on the current OS.
source to share
Looking back at the definition of these two patterns, we say that
-
Factory Method is used to define the interface for creating an object , but let the subclasses determine which class to create. Factory Method allows a class to wrap an instance into subclasses. "
-
Annotation Factory is used to create an interface for creating families of related or dependent objects without specifying their specific classes.
So you said it was correct. Factory Method refers to creating (usually) a single object, whereas Abstract Factory refers to multiple related objects.
But that's not all. If you look at the second word that I have highlighted in each intent, you will see another difference there, in terms of the mechanism that each template works.
-
Factory Method uses SUBCLASSES and inheritance to delegate an instance to a specific implementation. This means that to create new products, you need to inherit from the "creator" class and override the Factory method. This Factory method, in turn, returns the desired product.
-
On the other hand, Abstract Factory uses OBJECT function (i.e. factory) for delegation. You must make the code change in the product class, not in the creator class. Specifically, within a product class, you define several companion products (say, product ingredients), each of which can be created using Factory OBJECT (compiled in the product class and passed at runtime). The creator class in this case only creates an abstract product and goes into that Factory product that will be used by the product.
To make things a little confusing, the central Abstract Factory in Abstract Factory usually implements a Factory method. This central Factory often defines a series of Factory methods for all ingredients and delegates the creation of each ingredient to specific factories.
Hope this helps. Remember that many design patterns are really similar and in fact they are related, for example. look at Decorator pattern and adapter pattern. In most cases, the difference between the two design patterns lies in their respective intent. Good book on Design Patterns, by the way, what I really love is Head First Design Pattern . And there is a similar question posted here .
source to share