适配器模式:在双方的数据和行为都是正确的,又不容易修改时用适配器模式,将两者结合。应用于项目的维护。
目标类(Target)
namespace AdapterPattern.CLASS { abstract class Target { public virtual void Request() { Console.WriteLine("普通请求"); } } }
需要适配的类(Adaptee)
namespace AdapterPattern.CLASS { class Adaptee { public void SpecialRequest() { Console.WriteLine("特殊请求!"); } } }
适配器类(Adapter)
namespace AdapterPattern.CLASS { class Adapter:Target { private Adaptee adaptee = new Adaptee(); public override void Request() { adaptee.SpecialRequest(); } } }
测试类(TestMain)
namespace AdapterPattern { class TestMain { static void Main(string[] args) { Target target = new Adapter(); target.Request(); Console.WriteLine(); } } }
详细代码如下:
球员抽象类(Player)
namespace AdapterPatternTest.CLASS { abstract class Player { protected string name; public Player(string name) { this.name = name; } public abstract void Attach(); public abstract void Defence(); } }
前锋类(Forward)继承于球员类(Player)
namespace AdapterPatternTest.CLASS { class Forward:Player { public Forward(string name) : base(name) { } public override void Attach() { Console.WriteLine("前锋{0}进攻!",name); } public override void Defence() { Console.WriteLine("前锋{0}防守",name); } } }
后卫类(Defender)继承于球员类(Player)
namespace AdapterPatternTest.CLASS { class Defender:Player { public Defender(string name) : base(name) { } public override void Attach() { Console.WriteLine("前锋{0}进攻!",name); } public override void Defence() { Console.WriteLine("后卫{0}防守!", name); } } }
中锋由于不懂英语需要翻译,定义外籍中锋类
namespace AdapterPatternTest.CLASS { class ForeignCenter { private string name; public string Name { get { return name; } set { name = value; } } public void 进攻() { Console.WriteLine("外籍中锋{0}进攻!",name); } public void 防守() { Console.WriteLine("外籍中锋{0}防守!",name); } } }
定义翻译类(Traslater)继承于球员类
namespace AdapterPatternTest.CLASS { class Translator:Player { private ForeignCenter forCenter = new ForeignCenter(); public Translator(string name) : base(name) { forCenter.Name = name; } public override void Attach() { forCenter.进攻(); } public override void Defence() { forCenter.防守(); } } }
测试类(TestMain)
namespace AdapterPatternTest { class TestMain { static void Main(string[] args) { Player f = new Forward("巴特尔"); f.Attach(); Player d = new Defender("麦克格雷迪"); d.Defence(); Player forCenter = new Translator("姚明"); forCenter.Attach(); forCenter.Defence(); Console.ReadLine(); } } }
要么忍,要么狠,要么滚!