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

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

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

第一步:

将会变的和不变的分开:

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

第二步:

设计鸭子的行为:

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

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

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

相关文章:

  • 2021-06-24
  • 2021-04-04
  • 2022-12-23
  • 2021-10-25
  • 2022-12-23
  • 2022-01-02
猜你喜欢
  • 2021-07-24
  • 2021-08-06
  • 2021-12-16
  • 2022-12-23
  • 2021-11-29
  • 2021-11-15
  • 2021-06-07
相关资源
相似解决方案