Intent
We create objects without exposing the creation logic to users, we define an interface for creating objects, and allow subclasses to alter the type of objects that will be created after creating the objects in a superclass to prevent nasty codes.
Problem
Imagine that we have a restaurant application and the current menu includes only Italian food, and we put the methods of the menu operations in a class called Italian
. So, the bulk of our code lives inside the Italian
class.
Suppose now that the customers wanted to eat French food so we want to add the French
food to the menu, So now we have to deal with the Italian
class and when we introduce a new food to the menu we will get more and more complicated code.
Solution
The factory method design pattern tells us to replace direct object construction calls (using the new
operator) with calls to a factory method.
The objects are created via the new
operator by being called from the factory method.
Pros and Cons
Pros
- Modular expandability of the application.
- We can introduce new product types' into the program without breaking an existing user (client) code.
Cons
- We get a high number of required classes. So, the code may become more complicated.
Thank you, and goodbye.