Factory Method
Type : Creational design pattern
Intent
Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
Applicability
Use the Abstract Factory pattern when
- a system should be independent of how its products are created, composed, and represented.
- a system should be configured with one of multiple families of products.
- a family of related product objects is designed to be used together, and you need to enforce this constraint.
- you want to provide a class library of products, and you want to reveal just their interfaces, not their implementations.
Structure
Firstly, Abstract Factory pattern suggests is to explicitly declare interfaces for each distinct product of the product family
Then we should declare the Abstract Factory which is an interface with list of creation methods for all products that are part of the product family.
Members
Product Interface
All products will implement this inteface so that any classes that need to use products will refer to this interface instead of referring the concrete product class.
ConcreteProducts
Concrete products that implement the Product interface.
ConcreteFactories
Overrides the factory method to return an instance of a ConcreteProduct.
Creator
- Declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the factory method that returns a default ConcreteProduct object.
- May call the factory method to create a Product object.
Creator relies on its subclasses to define the factory method so that it returns an instance of the appropriate ConcreteProduct.
Outcome
- It isolates concrete classes. The Abstract Factory pattern helps you control the classes of objects that an application creates. Because a factory encapsulates the responsibility and the process of creating product objects, it isolates clients from implementation classes.
- It makes exchanging product families easy. The class of a concrete factory appears only once in an application—that is, where it’s instantiated. This makes it easy to change the concrete factory an application uses. It can use different product configurations simply by changing the concrete factory.
- It promotes consistency among products. When product objects in a family are designed to work together, it’s important that an application use objects from only one family at a time.
- Supporting new kinds of products is difficult. Extending abstract factories to produce new kinds of Products isn’t easy. That’s because the AbstractFactory interface fixes the set of products that can be created.