Tuesday, July 19, 2011

adapter pattern sample c++ code


The following is an example of adapter Design Pattern tested on RHEL 5 with gcc 4.1.2. 
The program will also work on visual studio with little or no modifications.


/**************************
 *  Sample Code 
 **************************/
#include <iostream>
#include <list>
#include <cstdlib>

using namespace std;

// Legacy account
class CLegacyAccount {
     private:
           int m_nNo;

     public:
           CLegacyAccount(int m_nNo) {
                this->m_nNo = m_nNo;
           }

           void m_legacyAccountPrint() {
                cout << "Display legacy account details " << m_nNo << endl;
           }
};

// Renewed interface
class CRenewedAccountIntf {
     public:
           virtual void m_display() = 0;
};

// Renewed account object
class CAccount : public CRenewedAccountIntf {
    private:
           string m_nNo;

     public:
           CAccount(string m_nNo) {
                this->m_nNo = m_nNo;
           }

           void m_display() {
                cout << "Display renewed account details " << m_nNo << endl;
           }
};

// Legacy account adapter to renewed interface
class CLegacyAccountAdapter : public CLegacyAccount, public CRenewedAccountIntf {
     public:
           CLegacyAccountAdapter(string m_nNo) :
           CLegacyAccount(atoi(m_nNo.c_str())) {
           }

           void m_display() {
                this->m_legacyAccountPrint();
           }
};


//main begins
int main(int argc, char **argv) {
    list<CRenewedAccountIntf*> accountList;
    accountList.push_back(new CAccount("accountholder 1"));
    accountList.push_back(new CAccount("accountholder 2"));
    accountList.push_back(new CLegacyAccountAdapter("12345"));

    while ( ! accountList.empty() ){
        CRenewedAccountIntf* obj = accountList.front();
        obj->m_display();
        accountList.pop_front();
    }
     return 0;
}

/*
OUTPUT:

[sgupta@rhel60x86 pattern]$ ./pattern
Display renewed account details accountholder 1
Display renewed account details accountholder 2
Display legacy account details 12345
[sgupta@rhel60x86 pattern]$
*/

No comments:

Post a Comment