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
AD

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:20points,
  • Rating points-10
Last comments
ИМ
Игорь МаксимовNov. 22, 2024, 11:51 a.m.
Django - Tutorial 017. Customize the login page to Django Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
Evgenii Legotckoi
Evgenii LegotckoiOct. 31, 2024, 2:37 p.m.
Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
A
ALO1ZEOct. 19, 2024, 8:19 a.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 7:51 a.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 11:02 a.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
Now discuss on the forum
Evgenii Legotckoi
Evgenii LegotckoiJune 24, 2024, 3:11 p.m.
добавить qlineseries в функции Я тут. Работы оень много. Отправил его в бан.
t
tonypeachey1Nov. 15, 2024, 6:04 a.m.
google domain [url=https://google.com/]domain[/url] domain [http://www.example.com link title]
NSProject
NSProjectJune 4, 2022, 3:49 a.m.
Всё ещё разбираюсь с кешем. В следствии прочтения данной статьи. Я принял для себя решение сделать кеширование свойств менеджера модели LikeDislike. И так как установка evileg_core для меня не была возможна, ибо он писался…
9
9AnonimOct. 25, 2024, 9:10 a.m.
Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

Follow us in social networks