Factory Method Design Pattern

Design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.

When to use it?

Use the Factory Method when

πŸ“’ you don’t know beforehand the exact types and dependencies of the objects your code should work with.

πŸ“’ you want to save system resources by reusing existing objects instead of rebuilding them each time.

πŸ“’ you want to provide users of your library or framework with a way to extend its internal components.

Pros & Cons

🟒 You avoid tight coupling between the creator and the concrete products.

🟒 Single Responsibility Principle. You can move the product creation code into one place in the program, making the code easier to support.

🟒 Open/Closed Principle. You can introduce new types of products into the program without breaking the existing client code.

πŸ”΄ The code may become more complicated since you need to introduce a lot of new subclasses to implement the pattern. The best-case scenario is when you’re introducing the pattern into an existing hierarchy of creator classes.

Code

To be updated.

References

Last updated