Author image

Adapter/Wrapper/Facade Design Pattern


Difficulty:
1/5


Here we will disambiguate the Adapter Wrapper Facade Software Design patterns.

A confused pattern, yes.
It has many names.
Adapter, Facade, Wrapper.
But they're all pretty much the same..

The Adapter (aka Facade aka Wrapper class) wraps a legacy class with a new interface into an updated class that respects the new interface.

It is most often used to make existing classes work with others (perhaps new ones) without modifying their source code. Many Windows WinAPI functions are an example of this.

Design

  • an interface (perhaps legacy) is not compatible with the current system needs
  • an abstract base class is created that specifies the desired interface
  • an adapter class is defined that publicly inherits the interface of the abstract class, and privately inherits the implementation of the legacy class
  • this adapter class “(impedance) matches” the new interface to the old implementation.

Subtle differences: These patterns are basically all the same thing, but there can be subtle differences based on context (and personally confusion in the programming community causes them). They mostly differ on where they are used:

  • Facades are typically a wrapper for a subsystem of one or more classes. Making changes to that set of objects is confusing, because you don't always know which object has the method you need to call. That's the time to write a Facade that provides high-level methods for all the complex operations you can do to the collection of objects.
  • Adapter is a class created & used in order to adapt a legacy class to updated system needs
  • A Wrapper can be any of the two above

In our example the old class LegacyRectangle  contains draw(), thus we define the interface IRectangle which declares draw() then the Adapter/Facade/Wrapper Rectangle class inherits from the legacy class and implements the interface, by implementing the interface's draw() method. It sets up the draw as it is required and calls the LegacyRectangle::draw() method with the proper parameters passed.

I used Windows 8.1 x86_64, Visual Studio 2017 to build the project.

Github

Github repository link.


0 likes