Adapter Design Pattern

Adapter Design Pattern


Client expects particular interface from the server that has a different interface. In this case you can write a software adapter that will convert the interface of the server into the interface that the client expects.




When to use this pattern:

Convert the interface of a class into another interface client expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces. This pattern is also known as wrapper.




#include <iostream>


typedef int Coordinate;

typedef int Dimension;

using namespace std;


// Desired interface

class Rectangle

{

  public:

    virtual void draw() = 0;

};


// Legacy component

class LegacyRectangle

{

  public:

    LegacyRectangle(Coordinate x1, Coordinate y1, Coordinate x2, Coordinate y2)

    {

        x1_ = x1;

        y1_ = y1;

        x2_ = x2;

        y2_ = y2;

        cout << "LegacyRectangle:  create.  (" << x1_ << "," << y1_ << ") => ("

          << x2_ << "," << y2_ << ")" << endl;

    }

    void oldDraw()

    {

        cout << "LegacyRectangle:  oldDraw.  (" << x1_ << "," << y1_ << 

          ") => (" << x2_ << "," << y2_ << ")" << endl;

    }

  private:

    Coordinate x1_;

    Coordinate y1_;

    Coordinate x2_;

    Coordinate y2_;

};


// Adapter wrapper

class RectangleAdapter: public Rectangle, private LegacyRectangle

{

  public:

    RectangleAdapter(Coordinate x, Coordinate y, Dimension w, Dimension h):

      LegacyRectangle(x, y, x + w, y + h)

    {

        cout << "RectangleAdapter: create.  (" << x << "," << y << "), width = " << w << ", height = " << h << endl;

    }

    virtual void draw()

    {

        cout << "RectangleAdapter: draw." << endl;

        oldDraw();

    }

};


int main()

{

  Rectangle *r = new RectangleAdapter(120, 200, 60, 40);

  r->draw();

}


Adapter pattern can be implemented either through inheritance or composition.

C++ implementation of class adapter inherits publicly from the target and privately from adaptee.

In object adapter, the adaptee is composed inside the adapter and its methods are called through pointer indirection.


When to use this pattern:

You want to use an existing class and its interface does not match the one you need.


Setup VSCode with Salesforce

Step by Step guide to setup VSCode with Salesforce Install vscode Install Salesforce CLI (developer.salesforce.com/tools/sfdxcli) Perform fo...