Adapter Pattern

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 accountclass LegacyAccount{int no;public:LegacyAccount(int no){this->no = no;}void legacyAccountPrint(){cout << "Display legacy account details " << no << endl;}};// Renewed interfaceclass RenewedAccountIntf{public:virtual void display() = 0;};// Renewed account objectclass 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 interfaceclass LegacyAccountAdapter : public LegacyAccount,public RenewedAccountIntf{public:LegacyAccountAdapter(string no) :LegacyAccount(atoi(no.c_str())){}void display(){this->legacyAccountPrint();}};// Test programint 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();}}


Display renewed account details accountholder 1Display renewed account details accountholder 2Display legacy account details 12345