The factory method pattern is used to defer instantiation to subclasses. Using this method, a class need only know when to instantiate a class, not what kind of subclass to create.
This pattern addresses a problem found in the AbtractButton swing class. Its subclasses JCheckBox and JRadioButton want to display different icons when clicked. It uses a factory method to let its subclasses decided which icon to display.
![]()
There are two primary forces
- To delegate responsiblity - knowledge can be localized to specific helper subclasses
- To provide expandability - subclasses can specify which objects to create
There are four main actors in the factory method:
- Creator - contains a factory method (FactoryMethod()) that creates and type Product. Another method (AnOperation()) uses the factory method.
- Product - The generic object created in the Creator.
- ConcreteCreator - The subclass of Creator that overloads the factory method to return a ConcreteProduct instead of a plain product.
- ConcreteProduct - The subclass of Product to be returned from the factory method in a ConcreteeCreator.
As shown, the creator calls the FactoryMethod() to get an object to be determined by a subclass. The creator only needs to know that it will be returning an object of type Product. A subclass, named ConcreteCreator here, then overloads the FactoryMethod() to return ConcreteProduct instead of Product.
Taken from dofactory
+
-
- Supports code reuse - the same Creator is used for *Creator
- Encourages encapsulation and delegation
- A change to the Product interface can propagatee
- A Creator can only act on Product properties of *Product
- To work with a class, you must derive from it.
There are two variations of this pattern.
Both can be found in this example.
- The factory method instantantiates the ConcreteProducts
- Subclasses of the Creator overload the factory method to instantiate Concrete Products
- Abstract Factory
- Template Method
- Prototype