本文共 1571 字,大约阅读时间需要 5 分钟。
适配器模式(Adapter):将一个类的接口转换成客户希望的另外一个接口,Adapter模式使原来由于接口不兼容而不能一起工作的那些类可以一起工作。
在想要使用一个已存在的类,但是如果它的接口,也就是它的方法和你的要求不相同的时候,就应该考虑使用适配器模式,两个类所做的事件相同或相似,但是具有不同的接口时要使用它
适配器模式在实现上就是利用一个类将接口不匹配的的接口重新封装一遍#include#include using namespace std;//class Player{ public: Player(){ } Player(string n):name(n){ } virtual void Attack() = 0; virtual void Defense() = 0;protected: string name;};//前锋class Forwards: public Player{ public: Forwards(string n):Player(n){ } void Attack() { cout << name << " 前锋攻击 " << endl; } void Defense() { cout << name << " 前锋防御 " << endl; }};//中锋class Center : public Player{ public: Center(string n):Player(n){ } void Attack() { cout << name << " 中锋攻击 " << endl; } void Defense() { cout << name << " 中锋防御 " << endl; }};//外籍运动员,chinaAttack,chinaDefences 接口不适用于Attack 与 Defences//但是两对接口的功能时类似的,//所以用适配器将接口转换一致,使得客户端的调用更加简单class ForeignCenter{ public: ForeignCenter(){ } ForeignCenter(string n):name(n){ } void chinaAttack(){ cout << name << " 外籍中锋攻击 " << endl; } void chinaDefences(){ cout << name << " 外籍中锋防御 " << endl; }protected: string name;};class Adapter : public Player{ public: Adapter(string n):foreign(new ForeignCenter(n)){ } void Attack() { foreign->chinaAttack(); } void Defense() { foreign->chinaDefences(); }private: ForeignCenter *foreign;};int main(){ Player *p1 = new Forwards("科比"); Player *p2 = new Center("乔丹"); Player *p3 = new Adapter("姚明"); p1->Attack(); p2->Attack(); p3->Attack(); p1->Defense(); p2->Defense(); p3->Defense(); return 0;}
转载地址:http://gxnwi.baihongyu.com/