Evgenii Legotckoi
Evgenii LegotckoiSept. 13, 2018, 6:01 a.m.

Generative Design Patterns - Abstract Factory

The reasons

  • Providing an interface for creating families of related or dependent objects without specifying their specific classes.
  • Hierarchy that encapsulates: many possible "platforms" and building a set of "products".
  • The new operator is considered harmful.

Problems

If an application is to be portable, it needs to encapsulate all dependencies of the target platform. These "platforms" can include: windowing system, operating system, database, etc. All too often this encapsulation is not designed up front, and many case statements or various #ifdef with options for all currently supported platforms are starting to breed like rabbits all over the code.

Discussion

Providing an abstraction layer that abstracts the creation of families of related or dependent objects without explicitly specifying their concrete classes. The factory object is responsible for providing services to create the entire family of classes on all supported platforms. Clients never create platform objects directly, they ask the factory to do it for them.

This mechanism makes it easy to change the family of derived class objects, since a particular factory object class only appears once in the application, where it is created. An application can provide the ability to modify an entire family of derived objects by simply instantiating another specific instance of the abstract factory.

Because the service provided by the factory object is so common, it is usually implemented as a Singleton. Or it can be implemented using static class methods in the case of the C++ programming language.

Structure

An abstract factory defines a factory method for each generated object. Each factory method encapsulates the new operator and concrete, platform-specific classes. Each "platform" is then modeled by a derived Factory class.

Example

The purpose of Abstract Factory is to provide an interface for creating families of related objects without specifying concrete classes. This model can be found in sheet metal stamping equipment used in the manufacture of automobiles. Stamping equipment is an abstract factory that creates auto parts. The same mechanism is used to stamp right side doors, left doors, right front fenders, left front fenders, hoods, etc. for different car models. Through the use of rollers to change stamping patterns, the specific grades produced by the machine can be changed within minutes.

Control List

  • Decide if "platform independence" and authoring services are causing problems in your code.
  • Derive a matrix of "platforms" and "products". For what platform, what classes are required.
  • Define a factory interface, which consists of a factory method for each spawned object.
  • Define a production class for each platform that encapsulates all references to the new operator.
  • The client must remove all references to new and use factory methods to create child objects.

Rules of thumb

  • Sometimes parent templates compete: there are times when either the Prototype template or the Abstract Factory template can be used with success. Otherwise, they complement each other: An Abstract Factory can store a set of prototypes from which objects can be cloned and returned. The Builder may use one of the other templates to implement the components to be created. Abstract Factory, Builder and Prototype can use Singleton in their implementation.
  • Abstract Factory, Builder and Prototype define a factory object that is responsible for creating a class of generated objects and makes it a system parameter. An abstract factory has a factory object or method that produces objects of multiple classes. The Builder has a factory object that builds a complex product incrementally using an appropriate complex protocol. A prototype has a factory object (aka prototype) that creates a product by copying the prototype object.
  • Abstract Factory classes are often implemented using Factory Methods, but they can also be implemented using Prototype.
  • Abstract Factory can be used as an alternative to Facade to hide platform-specific classes.
  • Builder focuses on building a complex object step by step. The abstract factory emphasizes a family of product objects (simple or complex). The Builder returns the product as the last step, but as far as the abstract factory is concerned, the product returns immediately.
  • Often projects start with Factory Method (less complex, customizable, subclasses proliferate) and evolve towards Abstract Factory, Prototype, or Builder (more flexible, more complex) as the developer finds that more flexibility is required when creating an object.
We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
e
  • ehot
  • March 31, 2024, 9:29 p.m.

C++ - Тест 003. Условия и циклы

  • Result:78points,
  • Rating points2
B

C++ - Test 002. Constants

  • Result:16points,
  • Rating points-10
B

C++ - Test 001. The first program and data types

  • Result:46points,
  • Rating points-6
Last comments
k
kmssrFeb. 9, 2024, 2:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 6:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 4:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 19, 2023, 5:01 a.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
a
a_vlasovApril 14, 2024, 1:41 p.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 9:35 a.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
Mm
Mind minglesApril 12, 2024, 7:42 a.m.
ASO Service Forum: Enhancing App Visibility and Reach Welcome to the ASO Service Forum, your ultimate destination for insights, discussions, and strategies revolving around App Store Optimization. ASO (App Store Optimization) is paramoun…
f
fastrexApril 4, 2024, 11:47 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks