您的位置:首页 > 编程语言 > C#

用C#改写Head First Design Patterns--Adapter 适配器(原创)

2009-07-08 15:46 507 查看
原作是把一只火鸡通过一个适配器,出来后就是一只鸭,神奇。

改成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();

}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: