Adaptor Pattern
- Structural Design Patterns
UML Diagram
Example of Adapter Design Pattern
Cat Header (Cat.h)
#ifndef CAT_H_
#define CAT_H_
class Cat
{
public:
virtual ~Cat() {}
virtual void Meow() = 0; // Virtual
};
#endif // CAT_H_
Living Cat (LivingCat.h)
#ifndef LIVINGCAT_H_
#define LIVINGCAT_H_
#include "Cat.h"
#include <string>
#include <iostream>
class LivingCat : public Cat {
private:
std::string _name;
public:
LivingCat(std::string name);
virtual ~LivingCat();
virtual void Meow();
};
LivingCat::LivingCat(std::string name) : _name(name) {} // Constructor
LivingCat::~LivingCat() {} // Deconstructor
void LivingCat::Meow() {
std::cout << _name << " is Meowing!\n";
}
#endif // LIVINGCAT_H_
Robot Cat (RobotCat.h)
#ifndef ROBOTCAT_H_
#define ROBOTCAT_H_
#include <string>
#include <iostream>
class RobotCat {
private:
std::string _name;
public:
RobotCat(std::string name);
virtual ~RobotCat();
void PlayMeowingSound();
};
RobotCat::RobotCat(std::string name): _name(name) {}
RobotCat::~RobotCat() {}
void RobotCat::PlayMeowingSound()
{
std::cout << _name << " is playing meowing sound\n";
}
#endif // ROBOTCAT_H_
Roboto Cat Adapter (RobotCatAdaptor.h)
#ifndef ROBOTCATADAPTER_H_
#define ROBOTCATADAPTER_H_
#include "Cat.h"
#include "RobotCatAdapter.h"
#include "RobotCat.h"
class RobotCat;
class RobotCatAdapter : public Cat {
private:
RobotCat * _RobotCat;
public:
RobotCatAdapter(RobotCat * robotCat);
virtual ~RobotCatAdapter();
virtual void Meow();
};
RobotCatAdapter::RobotCatAdapter(RobotCat * robotCat) : _RobotCat(robotCat){}
RobotCatAdapter::~RobotCatAdapter() {}
void RobotCatAdapter::Meow()
{
_RobotCat->PlayMeowingSound();
}
#endif // ROBOTCATADAPTER_H_
Cat Main File (CatMain.cpp)
#include "LivingCat.h"
#include "RobotCat.h"
#include "RobotCatAdapter.h"
int main()
{
Cat * livingCat = new LivingCat(std::string("Koko"));
livingCat->Meow();
RobotCat * robotCat = new RobotCat(std::string("Oliver"));
Cat * robotCatAdapter = new RobotCatAdapter(robotCat);
robotCatAdapter->Meow();
// Delete allocated memory from the Heap
delete livingCat;
delete robotCatAdapter;
delete robotCat;
}
Output
Koko is Meowing!
Oliver is playing meowing sound