Imagine that you are the boss of a factory, any factory producing any product you could imagine. You have a perfect creational algorithm that is being used. However, one day you decide to expand your business and open one more factory in another city. That means that you have to encapsulate your creational algorithm for old and new factories. This is what the Abstract Factory is about.
The Abstract Factory pattern
Abstract Factory is one of the creational patterns. It encapsulates the creational process of related or dependent objects. The most interesting thing here is that there is no need to specify the concrete classes of these objects.
Let's get down to business and create a TableFactory. We want to be an outstanding company, so like IKEA, we will be producing something that is easy to build. For this reason, it is also necessary to create the ToolsFactory. Before we begin implementing, it is important to clarify the definition of Abstract Factory. This pattern is creational, so in general, it should not modify the provided objects, it should just provide them in a simple manner.
First of all, let's define our Tableinterface and Kitchen and Office implementations of it:
Secondly, we need tools which we will provide for the full kit:
Third things third, it is time to create an AbstractFactory. We have all the pieces we need for our relational objects. For example, KitchenTableTools are related to KitchenTable. That means that we need to encapsulate the creational process in a TableFactory and we will finally get the Abstract Factory pattern.
Finally, let's test what we have created. Two lucky customers come to our shop, a cook and an office manager. They want to buy tables for work.
We’ve implemented a TableFactory that controls the creational process. Each factory implementation encapsulated its product. For example, KitchenFactory encapsulated KitchenTable and KitchenTableTools. One of the benefits is that we can be sure that we will get the correct TableTools with the corresponding Table.
1) Abstract Factory provides an interface (or abstract class) for creating a family of related objects without specifying their concrete classes.
2) Abstract Factory is based on composition: object creation occurs in a method that is accessed through the factory interface (or abstract class).
3) Abstract Factory ensures low coupling by decreasing concrete dependencies of classes in the running code.