Click here to see the Description of Adapter Design Pattern
Source Code with Example:
/* * File:adapter.cpp * This file is described the adapter Design Pattern with help of example * Author: Aplha * Date: 29 Dec 2020 */ //Header file #include<iostream> //Target interface class ITarget { public: virtual void Start()=0; virtual void Stop()=0; virtual void SetMotorType(std::string) = 0; }; //Motor Interface class IMotor { public: virtual void StartMotor()=0; virtual void StopMotor()=0; }; //Actual Motor Class class ActualMotor:public IMotor { void StartMotor() {std::cout<<"Actual Motor Start, call driver app"<<std::endl;} void StopMotor() {std::cout<<"Actual Motor Stop, call driver app"<<std::endl;} }; // Motor Simulator Class class MotorSimulator:public IMotor { void StartMotor() {std::cout<<"Motor Simulator Start for testing"<<std::endl;} void StopMotor() {std::cout<<"Motor Simulator Stop for testing"<<std::endl;} }; //Adapter Class class Adapter:public ITarget { IMotor* mp; Adapter(const Adapter &other) = delete; // Disallow copying void operator=(const Adapter &) = delete;// Disallow copying public: Adapter(); ~Adapter(); void Start(); //Get interface from Base class void Stop(); //Get interface from Base class void SetMotorType(std::string str); }; //Adapter definition Adapter::Adapter():mp(nullptr){} Adapter::~Adapter() { if(mp) delete mp; } void Adapter::Start() { if(mp) { mp->StartMotor(); } else std::cout<<"Motor is not set"<<std::endl; } void Adapter::Stop() { if(mp) { mp->StopMotor(); } else std::cout<<"Motor is not set"<<std::endl; } void Adapter::SetMotorType(std::string str) { if(str == "ActualMotor") { if(mp) delete mp; mp = new ActualMotor; } else if(str == "SimulatorMotor") { if(mp) delete mp; mp = new MotorSimulator; } else { std::cout<<"Motor type is not available"<<std::endl; if(mp) delete mp; } } //Client int main() { std::cout<<"In Main"<<std::endl; //Create the Target ITarget * tar = new Adapter; //Set the Actual Motor tar->SetMotorType("ActualMotor"); tar->Start(); tar->Stop(); //Set the Simulator Motor tar->SetMotorType("SimulatorMotor"); tar->Start(); tar->Stop(); delete tar; return 0; }
Compilation command:
g++ -std=c++11 adapter.cpp
Output:
In Main
Actual Motor Start, call driver app
Actual Motor Stop, call driver app
Motor Simulator Start for testing
Motor Simulator Stop for testing