#include <iostream>
using namespace std;
class Duck {
public:
virtual ~Duck() = default;
virtual void Quack() = 0;
virtual void Fly() = 0;
};
class Turkey {
public:
virtual ~Turkey() = default;
virtual void Gobble() = 0;
virtual void Fly() = 0;
};
class ConcreteTurkey : public Turkey {
public:
void Gobble() override { cout << "Turkey Gooble" << endl; }
void Fly() override { cout << "Turkey Fly." << endl; }
};
class ConcreteDuck : public Duck {
public:
void Quack() override { cout << "Quack." << endl; }
void Fly() override { cout << "ConcreteDuck Fly." << endl; }
};
//对象适配器,也即组合方式实现适配
class DuckAdapter : public Duck {
public:
DuckAdapter(Turkey &turkey) : _turkey(turkey) { }
void Quack() override { _turkey.Gobble(); }
void Fly() override { _turkey.Fly(); }
private:
Turkey &_turkey;
};
//类适配器, 多继承方式, 这里直接继承具体的类,而非接口或抽象类
class DuckAdapterClass : public ConcreteDuck, public ConcreteTurkey {
public:
void Quack() override { ConcreteTurkey::Gobble(); }
void Fly() override { ConcreteTurkey::Fly(); }
};
void UseDuck(Duck &duck) {
duck.Quack();
duck.Fly();
}
int main() {
ConcreteTurkey cturkey;
DuckAdapter duck_adapter(cturkey);
UseDuck(duck_adapter);
DuckAdapterClass duck_adapter_class;
UseDuck(duck_adapter_class);
return 0;
}
适配器模式-C++
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...