Abstract Factory Method(kit) provides an interface for creating suits of related objects without specifying their concrete classes
Consider an application which supports different standard of appearance and behavior. Each component in a standard should be used together. Hard-coding this standards will pose a problem as it will not be portable. We also should not mix the components that make up the standard.
The Abstract Factory method pattern solves this problem by providing the necessary interface for creating an appropriate class instance. And also enabling clients to work with interfaces, without worrying about the concrete classes.
The abstract factory method pattern can be used in cases where:
- Configuration of the system requires a suite of products.
- Implementation of products must be hidden and only their interface disclosed
- Suites of objects must be used together
- AbstractFactory: Interface for methods that create abstract products
- ConcreteFactory: Implementation for methods that create abstract products
- AbstractProduct: Interface for Product object
- ConcreteProduct: Implementation of the AbstractProduct interface.
- Client: Use interfaces declared by AbstractFactory and AbstractProduct classes.
- AbstractFactory transfers the responsibility of product object creation to its concrete sub- classes
- Promotes loose-coupling between client and concrete products
- Increased flexibility in code as new variants of products can be integrated without changes in client code
- Increased complexity in code due to increase in new interfaces and classes
Applications generally need one instance of a Factory, so they are typically implemented as Singletons. The AbstractFactory does not have an implementation for product creation and the
ConcreteProduct sub-classes commonly define factory methods for this purpose.
Following up on our cafe example:
There are now several new branches of the cafe and we have managed to change the language of the menu for each branch. But the owners now want each branch to have unique interior design. Each branch will have a different look, the pictures on the wall and the staff uniform should be different.
To solve this problem, we create interfaces for
StaffUniform. Then we create concrete classes that implement these interfaces. After that, we create an abstract
BranchFactory class that will return
StaffUniform objects. Lastly we will create a static class
FactoryCreator to generate
BranchFactory object based on the information passed.