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

本文通过C#代码实现了一个有趣的设计模式案例——将火鸡通过适配器模式转化为鸭子的行为特征。展示了如何使用接口、类及适配器来解决不同对象间的兼容性问题。

原作是把一只火鸡通过一个适配器,出来后就是一只鸭,神奇。

 

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值