原作是把一只火鸡通过一个适配器,出来后就是一只鸭,神奇。
改成C#的代码:
using System;
using System.Collections.Generic;using System.Linq;using System.Text;namespace Adapter
{ /// <summary> /// 鸭子接口 /// </summary> public interface Duck { //可以咵咵的叫 void quack(); void fly(); }/// <summary>
/// 火鸡接口 /// </summary> public interface Turkey { //可以咯咯的叫 void gobble(); void fly(); }}
using System;
using System.Collections.Generic;using System.Linq;using System.Text;namespace Adapter
{ class MallardDuck:Duck {#region Duck 成员
void Duck.quack()
{ System.Console.WriteLine("绿头鸭叫!"); }void Duck.fly()
{ System.Console.WriteLine("绿头鸭飞!"); }#endregion
}}
using System;
using System.Collections.Generic;using System.Linq;using System.Text;namespace Adapter
{//火鸡类
public class WildTurkey:Turkey {#region Turkey 成员
void Turkey.gobble()
{ System.Console.WriteLine("火鸡咯咯的叫!"); }void Turkey.fly()
{ System.Console.WriteLine("火鸡飞!"); }#endregion
}//火鸡适配器类
public class TurkeyAdapter : Duck { Turkey t;public TurkeyAdapter(Turkey t)
{ this.t = t; }#region Duck 成员
void Duck.quack()
{ t.gobble(); }void Duck.fly()
{ //火鸡的飞行距离太短了,必须多飞才能看上去像鸭子 for (int i = 0; i < 5; i++) { t.fly(); } }#endregion
}}
using System;
using System.Collections.Generic;using System.Linq;using System.Text;namespace Adapter
{ class Program { static void Main(string[] args) { //进去的是火鸡 Turkey t = new WildTurkey();//出来就是只鸭子了!
Duck d= new TurkeyAdapter(t); d.quack();System.Console.ReadLine();
} }}