//设计模式之适配器模式
//类适配器和对象适配器
/*适配器模式将类的接口转化成客户希望的另一个接口,适配器模式使得原本由于
接口不兼容而不能一起工作的那些类可以一起工作*/
#include<iostream>
#include<string>
using namespace std;
class Player
{
string m_name;
public:
Player(string name) :m_name(name) {};
string getname() { return m_name; }
virtual void Attack() = 0;
virtual void Defense() = 0;
};
class Forward :public Player
{
public:
Forward(string name) :Player(name) {};
void Attack()
{
cout << "前锋" << this->getname() << "进攻" << endl;
}
void Defense()
{
cout << "前锋" << this->getname() << "放手" << endl;
}
};
class Guard :public Player
{
public:
Guard(string name) :Player(name) {};
void Attack()
{
cout << "后卫" << this->getname() << "进攻" << endl;
}
void Defense()
{
cout << "后卫" << this->getname() << "放手" << endl;
}
};
class ForeignCenter
{
string m_name;
public:
void Setname(string name) { m_name = name; }
string Getname() { return m_name; }
void jingong()
{
cout << "中锋" << this->Getname() << "进攻" << endl;
}
void fangshou()
{
cout << "中锋" << this->Getname() << "放手" << endl;
}
};
class Translator :public Player, public ForeignCenter
{
public:
Translator(string name) :Player(name)
{
this->Setname(name);
}
void Attack()
{
this->jingong();
}
void Defense()
{
this->fangshou();
}
};
int main()
{
Player* b = new Forward("巴蒂尔");
b->Attack();
Player* m = new Guard("麦克格雷迪");
m->Attack();
Player* ym = new Translator("要命");
ym->Attack();
ym->Defense();
system("pause");
return 0;
}
类的适配通过多重继承来实现。
//对象适配器
#include<iostream>
#include<string>
using namespace std;
class Player
{
string m_name;
public:
Player(string name) :m_name(name) {};
string getname() { return m_name; }
virtual void Attack() = 0;
virtual void Defense() = 0;
};
class Forward :public Player
{
public:
Forward(string name) :Player(name) {};
void Attack()
{
cout << "前辈" << this->getname() << "进攻" << endl;
}
void Defense()
{
cout << "前锋" << this->getname() << "放手" << endl;
}
};
class Guard :public Player
{
public:
Guard(string name) :Player(name) {};
void Attack()
{
cout << "后卫" << this->getname() << "进攻" << endl;
}
void Defense()
{
cout << "后卫" << this->getname() << "放手" << endl;
}
};
class ForeignCeenter
{
string m_name;
public:
void setname(string name) { m_name = name; }
string getname() { return m_name; }
void jingong()
{
cout << "中锋" << this->getname() << "进攻" << endl;
}
void fangshou()
{
cout << "中锋" << this->getname() << "放手" << endl;
}
};
class Translator :public Player
{
ForeignCeenter* center;
public:
Translator(string name) :Player(name) {
center = new ForeignCeenter();
center->setname(name);
}
void Attack()
{
center->jingong();
}
void Defense()
{
center->fangshou();
}
};
int main()
{
Player* b = new Forward("巴蒂尔");
b->Attack();
Player* m = new Guard("买个克雷格");
m->Attack();
Player* ym = new Translator("要命");
ym->Attack();
ym->Defense();
system("pause");
return 0;
}
对象适配器类似。