Featured Post

Trie implementation in C

Adapter Design Pattern in C++

Adapter Design pattern converts the interface of a class into another interface that clients expect. It lets classes work together which is not possible otherwise because of incompatible interfaces. It is also called as Wrapper Classes.

Areas of usage :

  • If we need an existing class, and its interface does not match the one we need.
  • If we want to create a reusable class that cooperates with unrelated classes, that is, classes that don't necessarily have compatible interfaces.
  • If we need to use several existing subclasses, but it's impractical to adapt their interface by subclassing every one. An object adapter can adapt the interface of its parent class.

Here's a simple implementation for the Adapter Design Pattern in C++.
 
#include <iostream>

using namespace std;

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

class StandardCircle
{
public:
    StandardCircle(double radius)
    {
      radius_ = radius;
        cout << "StandardCircle:  create. radius = "<< radius_ << endl;
    }
    void oldDraw()
    {
        cout << "StandardCircle:  oldDraw. " << radius_ << endl;
    }
private:
    double radius_ ;
};

class CAdapter : public Circle, private StandardCircle  //Adapter Class
{
public:
    CAdapter( double diameter)
        : StandardCircle(diameter/2)
    {
        cout << "CAdapter: create. diameter = " << diameter << endl;
    }
    virtual void draw()
    {
        cout << "CAdapter: draw." << endl;
        oldDraw();
    }
};

int main()
{
    Circle*  c = new CAdapter(14);
    c->draw();
}

Comments

Post a Comment

Please post your valuable suggestions