官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 轮台县| 元谋县| 屏山县| 博罗县| 舒兰市| 拜城县| 获嘉县| 县级市| 策勒县| 石泉县| 郎溪县| 开江县| 都江堰市| 惠来县| 久治县| 固镇县| 平南县| 宁远县| 安化县| 佛山市| 叙永县| 彭州市| 襄垣县| 察哈| 商南县| 株洲县| 邮箱| 金平| 固安县| 锡林郭勒盟| 大竹县| 获嘉县| 曲沃县| 南汇区| 萨嘎县| 习水县| 松原市| 建水县| 宜昌市| 鄱阳县| 探索|