The Factory Method pattern is way of creating objects, but letting subclasses decided exactly which class to instantiate. All factory method encapsulates creation of object. Creator class creates the object of the product based on values supplied by the client.
In this example participant are:
Product Interface and product classes.
I created IColorProduct Interface. This interface implemented by 3 classes RedColor, GreenColor and BlueColor. Based on passed values by client, Creator class (ColorCreator) creates different classes.
- By using factory method we centralized creation of the objects in one location.
- Client who ever using factory method responsibility is only passing values. Based on values different color objects are returning. Client no need to know internal logic of creation of object.
- In future if we add new color class there is no impact on client code.
- Hinding object creation logic inside Factory class.