Created
December 31, 2017 22:44
-
-
Save FONQRI/50f0b2d2a69de4f4b66b37832fe9cda7 to your computer and use it in GitHub Desktop.
C++ Adapter Design Pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <algorithm> | |
#include <cstdlib> | |
#include <iostream> | |
#include <list> | |
#include <memory> | |
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 ~RenewedAccountIntf(); | |
virtual void display() = 0; | |
}; | |
RenewedAccountIntf::~RenewedAccountIntf() {} | |
// Renewed account object | |
class Account : public RenewedAccountIntf { | |
string no; | |
public: | |
Account(string no); | |
void display(); | |
}; | |
Account::Account(string no) { this->no = no; } | |
void Account::display() | |
{ | |
cout << "Display renewed account details " << no << endl; | |
} | |
// Legacy account adapter to renewed interface | |
class LegacyAccountAdapter : public LegacyAccount, public RenewedAccountIntf { | |
public: | |
LegacyAccountAdapter(string no); | |
void display(); | |
}; | |
LegacyAccountAdapter::LegacyAccountAdapter(string no) | |
: LegacyAccount(atoi(no.c_str())) | |
{ | |
} | |
void LegacyAccountAdapter::display() { this->legacyAccountPrint(); } | |
// Test program | |
int main() | |
{ | |
list<shared_ptr<RenewedAccountIntf>> accountList; | |
accountList.push_back(make_shared<Account>("accountholder 1")); | |
accountList.push_back(make_shared<Account>("accountholder 2")); | |
accountList.push_back(make_shared<LegacyAccountAdapter>("12345")); | |
while (!accountList.empty()) { | |
shared_ptr<RenewedAccountIntf> obj = accountList.front(); | |
obj->display(); | |
accountList.pop_front(); | |
} | |
accountList.erase(accountList.begin(), accountList.end()); | |
for (auto obj : accountList) { | |
obj->display(); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment