Adapter


Description:

Match interfaces of different classes

Intent

  • Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.
  • Wrap an existing class with a new interface.
  • Impedance match an old component to a new system

Example:

Note

Idea:

Check list

  1. Identify the players: the component(s) that want to be accommodated (i.e. the client), and the component that needs to adapt (i.e. the adaptee).
  2. Identify the interface that the client requires.
  3. Design a "wrapper" class that can "impedance match" the adaptee to the client.
  4. The adapter/wrapper class "has a" instance of the adaptee class.
  5. The adapter/wrapper class "maps" the client interface to the adaptee interface.
  6. The client uses (is coupled to) the new interface

Code:

#include <iostream>
#include <memory>
#include <vector>
#include <cmath>

using namespace std;

typedef int Coordinate;
typedef int Dimension;

class Rectangle{
public:
    virtual void draw() =0;
    virtual ~Rectangle() {}
};

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_;    
};

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();
}

Ouput:

LegacyRectangle:  create.  (120,200) => (180,240)
RectangleAdapter: create.  (120,200), width = 60, height = 40
RectangleAdapter: draw.
LegacyRectangle:  oldDraw.  (120,200) => (180,240)

results matching ""

    No results matching ""