一、概述
- 适配器模式,将一个类的接口转换成客户希望的另一个接口。Adapter 模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
- 一个很直观的例子就是电源适配器。不管电压有多高,都会适配成适用的电压。
- 系统的数据和行为都是正确的,但是接口不符合时候,应该考虑是用适配器,目的是使控制范围之外的一个原有对象与某个接口匹配。适配器模式主要应用于希望复用一些现存的类,但是接口又与复用环境要求不一致的情况。
二、代码举例
//球员类
abstract class Player
{
protected string name;
public Player(string name)
{
this.name = name;
}
public abstract void Attack();
public abstract void Defense();
}
//前锋类
class Forwards:Player
{
public Forwards(string name):base(name)
{
}
public override void Attack()
{
Console.WriteLine("前锋Attack");
}
public override void Defense()
{
Console.WriteLine("前锋Defense");
}
}
//中锋类
class Center:Player
{
public Forwards(string name):base(name)
{
}
public override void Attack()
{
Console.WriteLine("中锋Attack");
}
public override void Defense()
{
Console.WriteLine("中锋Defense");
}
}
//后卫类
class Guard:Player
{
public Forwards(string name):base(name)
{
}
public override void Attack()
{
Console.WriteLine("后卫Attack");
}
public override void Defense()
{
Console.WriteLine("后卫Defense");
}
}
//外籍运动员
class ForeignPlayer:Player
{
private string name;
public string Name{
get {return name;}
set {name = value;}
}
public void 进攻()
{
Console.WriteLine("后卫进攻");
}
public void 防守()
{
Console.WriteLine("后卫防守");
}
}
//翻译者
class Translator:Player
{
private ForeignPlayer forPlayer = new ForeignPlayer();
public Translator(string name): base(name)
{
forPlayer.Name = name;
}
public override Attack()
{
forPlayer.进攻();
}
public override Defense()
{
forPlayer.防守();
}
}
//客户端调用代码
static void Main(string[] args)
{
Player b = new Forwards("m1");
b.Attack();
Player m = new Forwards("m2");
m.Attack();
m.Defense();
Player n = new Translator("m3");
n.Attack();
n.Defense();
Console.Read();
}
网友评论