• 多变的鸭子策略模式


    模型鸭子,既有不飞的又能飞的,有多种颜色的。而且以后还会有新的需求。

    对于此如何用程序来既能准确表示而且又有很好的扩展性。

    将会变化的部分用接口的形式封装起来的,好让其他部分不会受到影响。

    第一步:

    将会变的和不变的分开:

    这里只拿出不飞和能飞拿出来举例。

    第二步:

    设计鸭子的行为:

    为鸭子建立一个飞的接口类。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace Bll.duck.Interface
    {
       public interface Ifly
        {
           string fly();
        }
    }
    
    

    建立2个类表示:不飞,能飞。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace Bll.duck
    {
       public class flywith:Interface.Ifly
        {
            public string fly()
            {
                return "我能飞";
            }
        }
    }
    
    

    整合鸭子行为

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace Bll.duck
    {
       public class nofly:Interface.Ifly
        {
            public string fly()
            {
                return "不能飞";
            }
        }
    }
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace Bll.duck
    {
       public class duck
        {
           Interface.Ifly fly;
           public string getfly()
           {
               fly = new flywith();
               return fly.fly();
           }
    
           public string getnofly()
           {
               fly = new nofly();
               return fly.fly();
           }
    
           public void setfly(Interface.Ifly flytyper)
           {
               fly = flytyper;
           }
        }
    }
    

    策略模式:是指将算法封装起来的,让它们之间可以相互替换。

  • 相关阅读:
    Pro ASP.NET Core MVC2
    vscode
    git命令使用
    单行函数
    过滤和排序
    oracle基本查询
    斐波那契数列的递归实现
    队列的顺序存储结构
    队列的链式存储结构
    折半查找法
  • 原文地址:https://www.cnblogs.com/linjiancun/p/1812088.html
Copyright © 2020-2023  润新知