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
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
m
moogoNov. 22, 2024, 7:17 a.m.
Mosquito Spray System Effective Mosquito Systems for Backyard | Eco-Friendly Misting Control Device & Repellent Spray - Moogo ; Upgrade your backyard with our mosquito-repellent device! Our misters conce…
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 для меня не была возможна, ибо он писался…

Follow us in social networks