适配器模式(Adapter),将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
适配器模式主要应用于希望复用一些现存的类,但是接口又与复用环境要求不一致的情况。
适配器模式有两种类型:类适配器模式和对象适配器模式。
DataAdapter用作DataSet和数据源之间的适配器以便检索和保存数据。DataAdapter通过映射Fill(这更改了DataSet中的数据以便与数据源中的数据相匹配)和Update(这更改了数据源中的数据以便与DataSet中的数据相匹配)来提供这一适配器。
Demo1:
class Target { public virtual void Request() { Console.WriteLine("普通请求!"); } }
class Adaptee { public void SpecialRequest() { Console.WriteLine("特殊请求!"); } }
class Adapter : Target { private Adaptee adaptee = new Adaptee(); public override void Request() { adaptee.SpecialRequest(); } }
Test:
Target target = new Adapter(); target.Request();
Demo2:
abstract class Player { protected string name; public Player(string name) { this.name = name; } public abstract void Attack(); public abstract void Defence(); }
class Forward : Player { public Forward(string name) : base(name) { } public override void Attack() { Console.WriteLine("前锋 {0} 进攻", name); } public override void Defence() { Console.WriteLine("前锋 {0} 防御", name); } }
class SpecialPlayer { private string name; public string Name { get { return name; } set { name = value; } } public void SpecialAttack() { Console.WriteLine("外籍球员 {0} 进攻",name); } public void SpecialDefence() { Console.WriteLine("外籍球员 {0} 防御", name); } }
class AdapterPlayer : Player { private SpecialPlayer sp = new SpecialPlayer(); public AdapterPlayer(string name) : base(name) { sp.Name = name; } public override void Attack() { sp.SpecialAttack(); } public override void Defence() { sp.SpecialDefence(); } }
Test:
Player p1 = new Forward("巴蒂尔"); p1.Attack(); p1.Defence(); Console.WriteLine(Environment.NewLine); Player sp = new AdapterPlayer("姚明"); sp.Attack(); sp.Defence();
时间: 2024-10-05 22:47:53