Skip to content
Dmitriy Kotov edited this page Jan 15, 2017 · 5 revisions

Overall information

Structural pattern

Used when there is a need to decouple Implementation classes from their Abstraction. Such decoupling is implemented via composing the Implementation class, inside of Abstraction class. Abstraction then delegates some function calls to Implementation class, that is located inside of it.


Advantages:

+ Decouples Abstraction from Implementation, allowing to change them independently.

+ Reduces complexity of class hierarchy when faced with multiple axis of changes in domain model.

Let's say we have an UI application, that is responsible for drawing client's report.

At UI we have the following elements:

  • Table
  • Image
  • TextArea

Assuming that we might have the following hierarchy of elements.

UiElement would be abstract base class for each and every element on UI. And it will have the following subclasses:

  • TableUiElement
  • ImageUiElement
  • TextAreaUiElement

And if the new element will appear, we will just introduce new subclass of UiElement class. This will work as long as there is only one axis of change (which represents possible elements at UI form).

Right now this application only support one platform (let's say Windows), but what if we want to introduce new platform (for example Linux)? Each subclass from UiElement will also have 2 more subclasses, representing each available platform, like TableUiElement -> WindowsTableUiElement and LinuxTableUiElement.

Such structure will contain just huge amount of classes, comparing to structure, presented in Bridge pattern.


Project example:

In this project we have example with the following model:

Automobile - abstract class with the following methods:

  • start() - starts automobile

  • stop() - stops automobile

  • travelTo(coordinates : Coordinates) - travels to provided coordinates

Automobile class has two subclasses - Bus and Truck.

Automobile also has an instance of a class Engine, which has the following methods:

  • start() - starts engine

  • stop() - stops engine

Engine has two subclasses - DieselEngine and ElectricEngine.

In this example i wanted to show you the benefit from using the Bridge pattern when faced with multiple axis of change.

In existing structure it is very easy to produce every possible combination of Automobile and Engine without creating concrete classes:

  • new Bus(new DieselEngine()) instead of creating DieselBus
  • new Bus(new ElectricEngine()) instead of creating ElectricBus
  • new Truck(new DieselEngine()) instead of creating DieselTruck and so on...

Introducing new type of Engine will not force us to create a subclass for each type of Automobile if we use Bridge pattern right here.

Clone this wiki locally