Evgenii Legotckoi
Evgenii LegotckoiSept. 24, 2018, 5:05 a.m.

Structural Design Patterns - Bridge

Goals

  • Separate the abstraction from its implementation so that they can change independently of each other.
  • Create a public interface in an inheritance hierarchy and implement it in your own inheritance hierarchy.
  • In addition to encapsulation, the use of isolation

Problems

"Strengthening programming relationships" by using a subclass of an abstract base class to provide alternative implementations. This blocks compile-time binding between interface and implementation. Abstraction and implementation cannot be independently extended or redefined.


Motivation

Consider the area of "thread scheduling".

There are two types of thread schedulers, two types of operating systems or "platforms". Given this approach to specialization, we must define a class for each of these two variations. If we add a new platform (say... the Java Virtual Machine), what would our hierarchy look like?

What if we had three kinds of thread schedulers and four kinds of platforms? What if we had five types of thread schedulers and ten types of platforms? The number of classes we would have to define is the result of the number of scheduling schemes and the number of platforms.

The Bridge design pattern suggests refactoring this exponentially explosive inheritance hierarchy into two orthogonal hierarchies - one for platform-independent abstractions and one for platform-dependent implementations.

Discussion

Decompose the component's interface and implementation into orthogonal class hierarchies. An interface class contains a pointer to an abstract implementation class. This pointer is initialized with an instance of the concrete class, but all subsequent interaction of the interface class with the implementation class is limited to the abstraction supported in the base implementation class. The client interacts with the interface class and in turn "delegates" all requests to the class implementation.

The interface object is the "handler" known and used by the client; while the implementation object or "body" is safely encapsulated to ensure that it can continue to evolve or be completely replaced (or used at runtime.

Use the Bridge pattern if:

  • You want the implementation to bind at runtime
  • you have an increase in the number of classes resulting from a coupled interface and multiple implementations,
  • you want to share the implementation among several objects,
  • you need to map orthogonal class hierarchies.

Consequences include:

  • object interface decomposition
  • improved extensibility (you can extend (e.g. subclass) abstraction and implementation hierarchies independently),
  • hiding details from customers.

Bridge is synonymous with the handler/body idiom. It is a design mechanism that encapsulates an implementation class within an interface class. The first is the body and the second is the handler. The handler is treated by the user as an actual class, but the work is done in the body. “The handle/body class idiom can be used to decompose a complex abstraction into smaller, more manageable classes. The idiom can reflect the sharing of a single resource by multiple classes that control access to it (for example, reference counting)."

Structure

The client doesn't want to deal with platform dependent details. The Bridge pattern encapsulates this complexity behind an abstract wrapper.

Bridge emphasizes the identification and separation of the "interface" abstraction from the "implementation" abstraction.

Example

The Bridge pattern separates the abstraction from its implementation so that they can vary independently. An example of a Bridge is a household switch that controls lights, ceiling fans, etc. The purpose of a switch is to turn a device on or off. In fact, the switch can be implemented as a pull chain, a simple on/off switch, or various dimmer switches.

Control List

  1. Decide if there are two possible orthogonal class hierarchies in the application. These independent hierarchies can be: abstraction/platform, or domain/infrastructure, or interface/interface, or interface/implementation.
  2. Develop a separation of concerns: what the client wants and what the platforms provide.
  3. Create a platform interface that is minimal, necessary and sufficient. Its purpose is to separate the abstraction from the platform.
  4. Define a derived class of this interface for each platform.
  5. Create a base abstraction class that has a "platform object" and delegates platform-specific functionality to it.
  6. Define abstraction class specializations, if necessary.

Rules of thumb

  • The adapter allows you to work with classes after they are developed; The bridge makes them work before they were designed.
  • The bridge is designed in advance so that the abstraction and implementation change independently. The adapter modernizes the code so that the classes work together.
  • State, Strategy, Bridge (and to some extent Adapter) have similar decision structures. They all share elements of the handler/body idiom. They differ in intent - that is, they solve different problems.
  • The structure of State and Bridge is identical (except that Bridge allows class hierarchies, while State only allows one). The two patterns use the same structure to solve different problems: State allows the behavior of an object to change along with its state, while the intent of the Bridge is to separate the abstraction from its implementation so that they can vary independently.
  • If class interfaces delegate the creation of their implementation classes (instead of directly creating/binding themselves), then the project typically uses the Abstract Factory pattern to create implementations of the objects.
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, 2: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. 8, 2024, 6:43 p.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, 10:30 a.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, 8:38 a.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. 18, 2023, 9:01 p.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 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 2:35 a.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 4:47 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…
AC
Alexandru CodreanuJan. 19, 2024, 11:57 a.m.
QML Обнулить значения SpinBox Доброго времени суток, не могу разобраться с обнулением значение SpinBox находящего в делегате. import QtQuickimport QtQuick.ControlsWindow { width: 640 height: 480 visible: tr…

Follow us in social networks