Adapter Pattern (7)

适配器模式:

       将一个类的接口转换成另一个客户希望的接口。适配器使得因为接口不同的类可以同时工作。

示例代码:

using System;

using System.Text;

using System.IO;

 

namespace Hello

{

   //Duck Interface

   public interface Duck

   {

      void quake();

      void fly();

   }

   //Turkey Interface

   public interface Turkey

   {

      void gobble();

      void fly();

   }

   //WildTurkey Class

   public class WildTurkey : Turkey

   {

      public void gobble()

      {

        Console.WriteLine("Gobble Gobble");

      }

      public void fly()

      {

        Console.WriteLine("I'm flying short distance");

      }

   }

   //Turkey Adapter

   public class TurkeyAdapter : Duck

   {

      Turkey turkey;

      public TurkeyAdapter(Turkey turkey)

      {

        this.turkey = turkey;

      }

      public void quake()

      {

        turkey.gobble();

      }

      public void fly()

      {

        turkey.fly();

      }

   }

   class Program

   {

      static void Main(string[] args)

      {

        WildTurkey wildTurkey = new WildTurkey();

        Duck duck = new TurkeyAdapter(wildTurkey);

        duck.quake();

        duck.fly();

      }

   }

}

posted @ 2011-10-03 12:39  Erebus_NET  阅读(98)  评论(0编辑  收藏  举报