The factory method pattern allows callers to create instances of objects by only knowing the protocol or the top level base class and not the exact implementation classes.
- Callers will never know any details about the implementation classes.
- The factory method incorporates the logic required to decide which implementation class to instantiate based on the criteria supplied by the caller.
- Callers must not know all the implementation classes, just the protocol or the base class.
- Depending components must only know about the protocol or the base class and the class exposing the factory method.
- This pattern allows changing the existing implementation classes or adding new ones without exposing these details to the components that rely on them.
- Factory Method: creation through inheritance. Prototype: creation through delegation.
The factory method selects the implementation class to instantiate based on the criteria supplied by the caller. The caller must know only a single type.
Example: Color Palette โ User needs to mention the name of the palette and all colors with respect to that set will be populated and ready.
Color Palette โ User needs to mention the name of the palette and all colors with respect to that set will be populated and ready.
Summary : The factory method pattern is a good choice if we want to prevent exposing all implementation classes to our callers.
_Note that the factory method design pattern cannot be applied when there is no common protocol or shared base class. _
Top comments (0)