Intent
To provide client with one of multiple sub-classes of a super class based in the clent's input.
Structure:
Participant:
Shopper (Client)
ProductFactory (Factory)
Product (The interface of object clent wanted)
Milk, Sugar (The real object that will be provided)
Collaboration:
A Clent Shopper provides an key to factory ProductFactory to ask for a milk product (object) idenfied by the key, which can be anything to predefined in advance. In this case, "milk" is the best key
The factory creates a Milk object and return it to Shopper
Consequence
This pattern take out the responsibility of instantiation of a class from client program to the factory class.
Advantage:
The intiation of product is separated from the client. Any change in the implementation of product will not affect the code of client shopper.
Disadvantage:
The factory must know when and what will be at the same time
The factory can only supply a simple object. It can not satisfy client's complex requirement, such as a combination of products.
The factory can not process the created object
Implementation
We can apply Singleton pattern on Factory class or make the factory's method to create object static
Sample Code (python):
product: Product
Milk
Sugar
factory: ProductFactory
client - Shopper
app
http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/factory.html