Java EE 8 Design Patterns and Best Practices
上QQ阅读APP看书,第一时间看更新

Explaining Abstract Factory

Sometimes, we need to create a family of objects in a project. Imagine that we have an e-commerce and we have various kinds of products such as cell phones, notebooks, and tablets. These products are objects of the same family. If we create objects throughout a software, we will face problems if we then need to modify the initialization process of this object.

Using Abstract Factory will help us to solve problems including a system which should be independent of how its products are created, a system that should use one of the multiple families of products, and a system that should work with objects which are designed to be used together. Using this pattern will be beneficial as it isolates concrete classes. This means that with this pattern, we can control which class of objects that can be initiated on software. Furthermore, it permits the exchange of products easily and provides consistency among products.

The Abstract Factory pattern creates a single point of creation for objects and if we need to change the algorithm of object creation, we need only modify the concrete factory. In the following diagram, you can see the structure of Abstract Factory and how it is designed:

In our example, the Abstract Factory's structure has three main classes—AbstractFactory, Product, and Sale. The concrete classes of AbstractFactory are CellPhoneFactory, NotebookFactory, and TabletFactory. CellPhoneFactory is a concrete class responsible for creating the concrete classes CellphoneProduct and CellphoneSale, NotebookFactory is a concrete class responsible for creating the concrete classes NotebookProduct and NotebookSale, and the TabletFactory is a concrete class responsible for creating the concrete classes TabletProduct and TabletSale. A Client is a class responsible for using AbstractFactory to create AbstractProduct and AbstractSale. The concrete factory is created at runtime and it then creates the concrete product and sale.

The Abstract Factory pattern is sometimes used with another pattern such as Singleton, which we described earlier. Abstract Factory is a single point of creation, and often we need only one instance of it in an entire system. With this, using a Singleton pattern can help us create a design better and more efficiently.

This pattern is often used in frameworks and APIs that have a difficult creation process for an object, such as connections or sessions.