Adapter Design Pattern

This is one of structural design pattern.

The adapter pattern is a design pattern that is used to allow two incompatible types to communicate.

Example: In one user database system all information regarding user info like name, phone number, emailid, address etc are stored. But to call the user all information is not required, only user name & phone number is sufficient. In this case we can create a new class adapter. This class will provide only those information which is required and hide unrequired information.

class User {
    string name;
    string phonenumber;
    string emailId;
    string address;
    public:
        User(string na, string ph, string email, string addr)
        {
            name = na;
            phonenumber = ph;
            emailId = email;
            address = addr;
        }
        string getName()
        {
            return name;
        }
        string getPhonenumber()
        {
            return phonenumber;
        }
};

class UserList {
    vector<User> list;
    public:
        UserList()
        {
            list.push_back(User("Anil", "123456", "anil.nahak", "Noida");
            list.push_back(User("Prashant", "9876", "prashant", "Bangalore");
        }
        vector<User> getList()
        {
            return list;   
        }       
};

class IUserInfo {
    public:
        virtual void getInfo() = 0;
};

class userInfo : public IUserInfo {
    UserList ul;
    public:
        void getInfo()
        {
            vector<User> vt =  ul.getInfo();
            for(auto list : vt)
            {
                cout<<list.getName()<<"  "<<list.getPhonenumber()<<endl;
            }
        }
};

class Client {
    IUserInfo *usr;
    public:
        Client(IUserInfo *u)
        {
            usr = u;
        }
        void getInfo()
        {
            usr->getInfo();
        }
};

int main()
{
    IUserInfo *uinfo = new UserInfo();
    Client c(uinfo);
    c.getInfo();
    return 0;
}

Comments

Popular posts from this blog

STL Questions

Producer Consumer problem using mutex

Interview questions