适配器模式(Adapter):将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的类可以一起工作。
使用场合:在双方都不太容易修改的时候再使用适配器模式适配。
- using System;
- /**
- * 适配器模式(Adapter):将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的类可以一起工作。
- * 使用场合:在双方都不太容易修改的时候再使用适配器模式适配。
- */
- namespace StuDesignMode.Adapter
- {
- #region 适配器模式
- interface ITarget
- {
- void Request();
- }
- class Adaptee
- {
- public void SpecificRequest()
- {
- Console.WriteLine("特殊请求!");
- }
- }
- class Adapter : ITarget
- {
- private Adaptee _adaptee = new Adaptee();
- public void Request()
- {
- _adaptee.SpecificRequest();
- }
- }
- #endregion
- #region 示例代码
- abstract class AbsPlayer
- {
- public string Name { get; set; }
- public AbsPlayer(string name)
- {
- this.Name = name;
- }
- //进攻
- public abstract void Attack();
- //防守
- public abstract void Defense();
- }
- //前锋
- class Forwards : AbsPlayer
- {
- public Forwards(string name) : base(name) { }
- public override void Attack()
- {
- Console.WriteLine("前锋{0}进攻!",this.Name);
- }
- public override void Defense()
- {
- Console.WriteLine("前锋{0}防守!", this.Name);
- }
- }
- //中锋
- class Center : AbsPlayer
- {
- public Center(string name) : base(name) { }
- public override void Attack()
- {
- Console.WriteLine("中锋{0}进攻!",this.Name);
- }
- public override void Defense()
- {
- Console.WriteLine("中锋{0}防守!", this.Name);
- }
- }
- //后卫
- class Guaids : AbsPlayer
- {
- public Guaids(string name) : base(name) { }
- public override void Attack()
- {
- Console.WriteLine("后卫{0}进攻!", this.Name);
- }
- public override void Defense()
- {
- Console.WriteLine("后卫{0}防守!", this.Name);
- }
- }
- //外籍中锋
- class ForeignCenter
- {
- public string Name { get; set; }
- public void 进攻()
- {
- Console.WriteLine("外籍中锋{0}进攻!",this.Name);
- }
- public void 防守()
- {
- Console.WriteLine("外籍中锋{0}防守!", this.Name);
- }
- }
- //翻译(适配器)
- class Translator : AbsPlayer
- {
- private ForeignCenter _fgCenter;
- public Translator(string name)
- : base(name)
- {
- _fgCenter = new ForeignCenter();
- _fgCenter.Name = name;
- }
- public override void Attack()
- {
- _fgCenter.进攻();
- }
- public override void Defense()
- {
- _fgCenter.防守();
- }
- }
- //测试
- class ClientTest
- {
- static void Main(string[] args)
- {
- AbsPlayer SF = new Forwards("巴蒂尔");
- AbsPlayer SG = new Guaids("麦迪");
- AbsPlayer C = new Center("霍华德");
- AbsPlayer FC = new Translator("姚明");
- SF.Attack();
- SG.Attack();
- C.Attack();
- FC.Attack();
- SF.Defense();
- SG.Defense();
- C.Defense();
- FC.Defense();
- Console.WriteLine();
- }
- }
- #endregion
- }