Adapter

Originally published 2016-02-24 · Boris Ivanov

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:

2. UML class diagram

Class Adapter


3. Pros Class Adapter

3.1 Cons Class Adapter

4. Pros Object Adapter

4.1 Cons Object Adapter

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