博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
用C#改写Head First Design Patterns--Adapter 适配器(原创)
阅读量:4134 次
发布时间:2019-05-25

本文共 1448 字,大约阅读时间需要 4 分钟。

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

 

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

    
        }
    }
}

 

转载地址:http://eppvi.baihongyu.com/

你可能感兴趣的文章
C语言-变量类型
查看>>
C语言-static和extern关键字1-对函数的作用
查看>>
C 语言-static和extern关键字2-对变量的作用
查看>>
【JavaScript 教程】浏览器—History 对象
查看>>
还不会正则表达式?看这篇!
查看>>
100道+ JavaScript 面试题,助你查漏补缺
查看>>
JavaScript深入理解之闭包
查看>>
这才是学习Vite2的正确姿势!
查看>>
7 个适用于所有前端开发人员的很棒API,你需要了解一下
查看>>
25个构建Web项目的HTML建议,你需要了解一下!
查看>>
【web素材】02-10款大气的购物商城网站模板
查看>>
6种方式实现JavaScript数组扁平化(flat)方法的总结
查看>>
如何实现a===1 && a===2 && a===3返回true?
查看>>
49个在工作中常用且容易遗忘的CSS样式清单整理
查看>>
20种在学习编程的同时也可以在线赚钱的方法
查看>>
隐藏搜索框:CSS 动画正反向序列
查看>>
12 个JavaScript 特性技巧你可能从未使用过
查看>>
127个超级实用的JavaScript 代码片段,你千万要收藏好(上)
查看>>
【视频教程】Javascript ES6 教程27—ES6 构建一个Promise
查看>>
【5分钟代码练习】01—导航栏鼠标悬停效果的实现
查看>>