多变的鸭子-策略模式

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

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

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

第一步:

将会变的和不变的分开:

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

第二步:

设计鸭子的行为:

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

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

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

posted @ 2010-08-29 22:05  二锅头  阅读(269)  评论(0)    收藏  举报