Adapter

1. Usage

Converts interface of one class which required into another interface which can be called. This pattern also knows as Wrapper. Can be useful with Legacy classes which cannot be changed. It can be implemented 2 ways:

  • Class Adapter: Adapter sub-class required class and at same time implement interface client want to use. Such way proper method of required class can be called
  • Object Adapter: Uses Composition instead of inheritance. Adapter has instance of required class and call it by cleint request.

2. UML class diagram

Class Adapter

3. Pros Class Adapter

  • Less code than Object Adapter
  • Can override Adaptee behaviour as required

3.1 Cons Class Adapter

  • Requires subclassing.(if its a problem)
  • Less flexible than Object Adapter

4. Pros Object Adapter

  • More flexible than Class Adapter
  • Does not require inheritance

4.1 Cons Object Adapter

  • Harder to override Adaptee behaviour
  • Requires more code to implement properly

5. Source code

/*
 * Adapter Design Pattern (also Wrapper)
 * By Boris Ivanov (C) 2016
 * /
#include <iostream>
#include <math.h>

using namespace std;

class AdapterInterface{

    virtual void draw(float , float ) = 0;
};

class CartesianDrawer{
protected:
    void drawXY(float x, float y){
        cout << "Drawing Point(" << x << "," << y << ")" << endl;
    }
};

class Polar2CartesianAdapterDrawer: public AdapterInterface, private CartesianDrawer{
public:
    virtual void draw(float R, float Phi){
        float x = R * cos(Phi);
        float y = R * sin(Phi);
        drawXY(x, y);
    }
};


int main(int argc, char *argv[])
{
    Polar2CartesianAdapterDrawer adapter;
    adapter.draw(10, 3.1415926/4);
    return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *