GOOD:双方都不适合修改的时候,可以考虑使用适配器模式
例:
#include <iostream>
using namespace std;
class Target
{
public:
virtual void Request()
{
cout<<"普通的请求"<<endl;
}
};
class Adaptee
{
public:
void SpecificalRequest()
{
cout<<"特殊请求"<<endl;
}
};
class Adapter :public Target
{
private:
Adaptee* ada;
public:
virtual void Request()
{
ada->SpecificalRequest();
Target::Request();
}
Adapter()
{
ada=new Adaptee();
}
~Adapter()
{
delete ada;
}
};
客户端:
int main()
{
Adapter * ada=new Adapter();
ada->Request();
delete ada;
return 0;
}
例二
#include <iostream>
#include <string>
using namespace std;
class Player
{
protected:
string name;
public:
Player(string strName) { name = strName; }
virtual void Attack()=0;
virtual void Defense()=0;
};
class Forwards : public Player
{
public:
Forwards(string strName):Player(strName){}
public:
virtual void Attack()
{
cout<<name<<"前锋进攻"<<endl;
}
virtual void Defense()
{
cout<<name<<"前锋防守"<<endl;
}
};
class Center : public Player
{
public:
Center(string strName):Player(strName){}
public:
virtual void Attack()
{
cout<<name<<"中场进攻"<<endl;
}
virtual void Defense()
{
cout<<name<<"中场防守"<<endl;
}
};
//为中场翻译
class TransLater: public Player
{
private:
Center *player;
public:
TransLater(string strName):Player(strName)
{
player = new Center(strName);
}
virtual void Attack()
{
player->Attack();
}
virtual void Defense()
{
player->Defense();
}
};
客户端
int main()
{
Player *p=new TransLater("小李");
p->Attack();
return 0;
}