适配器模式 The Adapter Pattern
2008-06-26 17:04
246 查看
适配器模式——将一个类的接口,转换成客户期望的另一个接口。适配器让原本接口不兼容的类可以合作无间。(摘自《Head First Design Patterns》)
以下是自已用VS画了一个简图:
创建大型武器和小型武器的接口:
实现一个大型武器和二个小型武器:
本来令狐冲只能拿着小型武器攻击,适配器要达到的目的就是让令狐冲也能用大型武器,下面是令狐冲的类:
可见,他耍的独孤九剑第一式和第二式都只能用小型武器,要想让他用大型武器,就得为他创建一个适配器:
把斧子适配成小型武器就可以让令狐冲耍独孤九剑了,下面测试一下:
输出结果:
独孤九剑第一式:轮斧生风,势不可挡!落斧劈砍,金钢可破!
独孤九剑第一式:挥动匕首,扰敌心智!匕首刺杀,以快致胜!
独孤九剑第一式:随风舞剑,可防可攻!借风刺剑,无人可挡!
--------------
关于独孤九剑第二式就暂不测试了,呵呵。
以下是自已用VS画了一个简图:
创建大型武器和小型武器的接口:
interface IBigWeapon { void Chop(); void Wheel(); } interface ISmallWeapon { void Brandish(); void Pierce(); }
实现一个大型武器和二个小型武器:
class Axe : IBigWeapon { #region BigWeapon 成员 public void Chop() { Console.Write("落斧劈砍,金钢可破!"); } public void Wheel() { Console.Write("轮斧生风,势不可挡!"); } #endregion } class Knife : ISmallWeapon { #region ISmallWeapon 成员 public void Brandish() { Console.Write("挥动匕首,扰敌心智! "); } public void Pierce() { Console.Write("匕首刺杀,以快致胜! "); } #endregion } class Sword : ISmallWeapon { #region ISmallWeapon 成员 public void Brandish() { Console.Write("随风舞剑,可防可攻!"); } public void Pierce() { Console.Write("借风刺剑,无人可挡!"); } #endregion }
本来令狐冲只能拿着小型武器攻击,适配器要达到的目的就是让令狐冲也能用大型武器,下面是令狐冲的类:
class Linghuchong { public void Attack1(ISmallWeapon weapon) { Console.WriteLine(""); Console.Write("独孤九剑第一式:"); weapon.Brandish(); weapon.Pierce(); } public void Attack2(ISmallWeapon weapon) { Console.WriteLine(""); Console.Write("独孤九剑第二式:"); weapon.Pierce(); weapon.Brandish(); } }
可见,他耍的独孤九剑第一式和第二式都只能用小型武器,要想让他用大型武器,就得为他创建一个适配器:
class BigWeaponAdapter : ISmallWeapon { private IBigWeapon BigWeapon; #region ISmallWeapon 成员 public void Brandish() { this.BigWeapon.Wheel(); } public void Pierce() { this.BigWeapon.Chop(); } #endregion public BigWeaponAdapter(IBigWeapon weapon) { this.BigWeapon = weapon; } }
把斧子适配成小型武器就可以让令狐冲耍独孤九剑了,下面测试一下:
Linghuchong lhc = new Linghuchong(); IBigWeapon axe = new Axe(); ISmallWeapon knife = new Knife(); ISmallWeapon sword = new Sword(); ISmallWeapon axeAdapter = new BigWeaponAdapter(axe); //lhc.Attack1(axe);//产生异常 //用适配器 lhc.Attack1(axeAdapter); lhc.Attack1(knife); lhc.Attack1(sword);
输出结果:
独孤九剑第一式:轮斧生风,势不可挡!落斧劈砍,金钢可破!
独孤九剑第一式:挥动匕首,扰敌心智!匕首刺杀,以快致胜!
独孤九剑第一式:随风舞剑,可防可攻!借风刺剑,无人可挡!
--------------
关于独孤九剑第二式就暂不测试了,呵呵。
相关文章推荐
- 设计模式(七)The Adapter and Facade Pattern 适配器模式与外观模式
- 适配器模式 The Adapter Pattern
- [译] The Adapter Pattern 适配器模式 from Ch7 of《Design Patterns Explained》
- 适配器模式(Adapter Pattern)
- 适配器模式(Adapter Pattern)
- .NET设计模式(8):适配器模式(Adapter Pattern)
- 二十四种设计模式:适配器模式(Adapter Pattern)
- 适配器模式(Adapter Pattern)
- 设计模式 - 适配器模式(adapter pattern) 枚举器和迭代器 具体解释
- C#设计模式(7)——适配器模式(Adapter Pattern) 推荐
- C#设计模式——适配器模式(Adapter Pattern)
- 适配器模式(Adapter Pattern)
- 设计模式――适配器模式(Adapter Pattern)
- 适配器模式(Adapter Pattern)
- 适配器模式(Adapter Pattern)
- 设计模式系列(十)适配器模式(Adapter Pattern)
- 第6章 适配器模式(Adapter Pattern)
- .Net设计模式之适配器模式(Adapter Pattern)
- Java设计模式——适配器模式(Adapter Pattern)
- 23种设计模式之-----适配器模式(Adapter Pattern)