多变的鸭子-策略模式

本文介绍如何使用策略模式来设计鸭子的飞行行为,通过定义飞行接口及其实现类,实现不同鸭子的飞行特性,并保持良好的扩展性和代码复用。

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

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

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

第一步:

将会变的和不变的分开:

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

第二步:

设计鸭子的行为:

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

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

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

转载于:https://www.cnblogs.com/linjiancun/archive/2010/08/29/1812088.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值