zoukankan      html  css  js  c++  java
  • 多变的鸭子策略模式

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

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

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

    第一步:

    将会变的和不变的分开:

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

    第二步:

    设计鸭子的行为:

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

    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;
           }
        }
    }
    

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

  • 相关阅读:
    hibernate--could not initialize proxy
    20160509-hibernate--继承映射
    CF1111C Creative Snap
    CF1097D Makoto and a Blackboard
    CF1091D New Year and the Permutation Concatenation
    CF1096D Easy Problem
    CF1076E Vasya and a Tree
    CF1081C Colorful Bricks
    CF1081E Missing Numbers
    CF1093D Beautiful Graph
  • 原文地址:https://www.cnblogs.com/linjiancun/p/1812088.html
Copyright © 2011-2022 走看看