您的位置:首页 > 其它

适配器模式 The Adapter Pattern

2008-06-26 17:04 246 查看
          适配器模式——将一个类的接口,转换成客户期望的另一个接口。适配器让原本接口不兼容的类可以合作无间。(摘自《Head First Design Patterns》)

        以下是自已用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);


       输出结果:

       独孤九剑第一式:轮斧生风,势不可挡!落斧劈砍,金钢可破!
       独孤九剑第一式:挥动匕首,扰敌心智!匕首刺杀,以快致胜!
       独孤九剑第一式:随风舞剑,可防可攻!借风刺剑,无人可挡!

       --------------
       关于独孤九剑第二式就暂不测试了,呵呵。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  class interface 测试