Evgenii Legotckoi
Evgenii LegotckoiSept. 21, 2018, 7:11 a.m.

Structural Design Patterns - Adapter

Goals

  1. Converting a class interface to another interface. An adapter allows classes to work together that might otherwise be due to incompatible class interfaces.
  2. Wrapping an existing class in a new interface
  3. Compliance of the old component with the new system

Problems

A ready-made component has everything you need to develop your system, but its interfaces are incompatible with the interfaces of your application classes.


Discussion

Reuse has always been painful. One of the reasons was the problem in creating something new while reusing something old. There is always something not quite right or not quite compatible between the old and the new. It could be physical dimensions. It could be sync. These may be unfortunate assumptions or competing standards.

This is similar to the problem of inserting a new three-prong electrical plug into an old two-prong socket - some kind of adapter or intermediary is needed.

An adapter is a creation of an intermediate abstraction that translates or maps an old component into a new system. Clients call methods on the Adapter object that redirect them to calls to the inherited bean. This strategy can be implemented with either inheritance or aggregation.

The adapter functions as a wrapper or modifier on an existing class. It provides a different or translated representation of that class.

Structure

Below, the deprecated display() method for the Rectangle component used in the Rectangle expects to receive "x, y, w, h" parameters. But the client wants to pass "top left x and y" and "bottom right x and y". This inconsistency can be corrected by adding an additional layer of abstraction - i.e. an adapter object.

The adapter can also be thought of as a "wrapper".

Example

The adapter pattern allows other incompatible classes to work together by converting the interface of one class into the interface expected by clients. Female sockets are an example of an adapter. The socket is attached to the ratchet, provided that the size of the actuator is the same. Typical disc sizes in the US are 1/2" and 1/4". Obviously a 1/2" ratchet will not "fit into a 1/4" socket unless an adapter is used. The 1/2" to 1/4" adapter has a 1/2" female connection to mount on a 1/2" shaker and a 1/4" male connection to mount to a 1/4" socket.

Control List

  1. Define the players: the component(s) you want to use (i.e. client) and the component you want to adapt (i.e. adaptable).
  2. Determine the interface that the client requires.
  3. Create a "wrapper" class that can "match the interface" of the client.
  4. The adapter/wrapper class "has" an instance of the class being adapted.
  5. The adapter/wrapper class "maps" the client interface to the adapted interface.
  6. The client uses a new interface

Rules of thumb

  • Adapter allows classes to work after they are designed; The bridge makes them work before they are developed.
  • The bridge is designed in advance so that the abstraction and implementation change independently. The adapter upgrades so that collaborative classes work together.
  • An adapter provides a different interface to its object. The proxy provides the same interface. The decorator provides an extended interface.
  • The adapter is designed to change the interface of an existing object. A decorator improves the performance of another object without changing its interface. The decorator is thus more transparent to the application than the adapter. As a consequence, the Decorator supports recursive composition, which is not possible with pure adapters.
  • Facade defines a new interface, while Adapter uses the old interface. Remember that an adapter supports two existing interfaces, not defines a completely new one.
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
  • April 1, 2024, 2:29 a.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, 7: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, 11: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, 9: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, 10: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, 6:41 p.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 2:35 p.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 4:47 p.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…
AC
Alexandru CodreanuJan. 20, 2024, 12:57 a.m.
QML Обнулить значения SpinBox Доброго времени суток, не могу разобраться с обнулением значение SpinBox находящего в делегате. import QtQuickimport QtQuick.ControlsWindow { width: 640 height: 480 visible: tr…

Follow us in social networks