Monday, June 13, 2011

What is Adapter pattern ?

  • Adapter pattern is a structural design pattern.
  • Also referred as wrapper pattern.
  • An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface.
  • The adapter translates calls to its interface into calls to the original interface.
  • The adapter is also responsible for transforming data into appropriate forms.
  • The adapter is created by implementing or inheriting both the interface that is expected and the interface that is pre-existing.
  • It is typical for the expected interface to be created as a abstract class.

Demonstrate a simple adapter pattern using C++

#include <iostream>
#include <list>
#include <cstdlib>
using namespace std;

// Legacy account
class LegacyAccount
{
    int no;

public:
    LegacyAccount(int no)
    {
        this->no = no;
    }

    void legacyAccountPrint()
    {
        cout << "Display legacy account details " << no << endl;
    }
};

// Renewed interface
class RenewedAccountIntf
{
public:
    virtual void display() = 0;
};

// Renewed account object
class Account : public RenewedAccountIntf
{
    string no;

public:
    Account(string no) {
        this->no = no;
    }

    void display()
    {
        cout << "Display renewed account details " << no << endl;
    }
};

// Legacy account adapter to renewed interface
class LegacyAccountAdapter : public LegacyAccount,
        public RenewedAccountIntf
{
public:
    LegacyAccountAdapter(string no) :
        LegacyAccount(atoi(no.c_str()))
    {
    }

    void display()
    {
        this->legacyAccountPrint();
    }
};


// Test program
int main()
{
    list<RenewedAccountIntf*> accountList;
    accountList.push_back(new Account("accountholder 1"));
    accountList.push_back(new Account("accountholder 2"));
    accountList.push_back(new LegacyAccountAdapter("12345"));

    while ( ! accountList.empty() )
    {
        RenewedAccountIntf* obj = accountList.front();
        obj->display();
        accountList.pop_front();
    }
}
OUTPUT:-
Display renewed account details accountholder 1
Display renewed account details accountholder 2
Display legacy account details 12345

2 comments :

  1. Very good example.Thanks

    ReplyDelete
  2. Thank you. I was looking for something other than the shape example.

    ReplyDelete

Contact Form

Name

Email *

Message *

Back to Top