设计模式 - 14)适配器模式
已有的双方无法很好的配合起来时,通过适配器,打通两者的联系。
class Target
{
public virtual void Request()
{
Console.WriteLine("普通请求");
}
}
class Adaptee
{
public void SpecificRequest()
{
Console.WriteLine("特殊请求");
}
}
class Adapter : Target
{
Adaptee adaptee = new Adaptee();
public override void Request()
{
adaptee.SpecificRequest();
}
}
Target tar = new Adapter();
tar.Request();
姚明刚去 NBA 时,教练可以直接对美国球员部署战术,但是姚明听不懂,这个时候需要一名翻译,由教练对翻译说,翻译对姚明说,然后姚明执行。
abstract class Player
{
protected string Name;
public Player(string name)
{
this.Name = name;
}
public abstract void Attack();
public abstract void Defense();
}
class Center : Player
{
public Center(string name) : base(name) { }
public override void Attack()
{
Console.WriteLine(string.Format("中锋{0}进攻", Name));
}
public override void Defense()
{
Console.WriteLine(string.Format("中锋{0}防守", Name));
}
}
class ForeignCenter
{
string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
public void 进攻()
{
Console.WriteLine(string.Format("外籍中锋{0}进攻", Name));
}
public void 防守()
{
Console.WriteLine(string.Format("外籍中锋{0}防守", Name));
}
}
class Translator : Player
{
ForeignCenter fc = new ForeignCenter();
public Translator(string name) : base(name)
{
fc.Name = name;
}
public override void Attack()
{
fc.进攻();
}
public override void Defense()
{
fc.防守();
}
}
// 业务代码:
Player b = new Center("斯科拉");
Player x = new Translator("姚明");
b.Attack();
x.Attack();
x.Defense();