设计模式(二)——策略模式

来源:互联网 发布:wet n wild靠谱淘宝店 编辑:程序博客网 时间:2024/06/06 06:55

策略模式(Strategy)

策略模式定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。

代码

我们来实现一个简单的商场收银软件功能来阐述策略模式:
1.我们先来定义一个收费方式的基类,代码如下:

现金收取抽象类

using System;namespace Strategy{//收费的基类public abstract class CashSuper{//收取的现金public abstract double AcceptCash(double money);}}

2.收费方案,代码如下:

正常收费子类

using System;namespace Strategy{//正常收费子类public class CashNormal:CashSuper{public override double AcceptCash(double money){return money;}}}

打折收费子类

using System;namespace Strategy{//打折收费子类public class CashRebate:CashSuper{//打的折扣private double moneyRebate=1;public CashRebate(string moneyRebate){this.moneyRebate=double.Parse(moneyRebate);}public override double AcceptCash (double money){return money*moneyRebate;}}}

返利收费子类

using System;namespace Strategy{//返利收费子类public class CashReturn:CashSuper{//返现条件private double moneyCondition=0;//返现的金额private double moneyReturn=0;public CashReturn (string moneyCondition,string moneyReturn){this.moneyCondition = double.Parse (moneyCondition);this.moneyReturn = double.Parse (moneyReturn);}public override double AcceptCash(double money){double result=money;if (money >= moneyCondition) {result = money - Math.Floor (money / moneyCondition) * moneyReturn;}return result;}}}

3.现金收取类,代码如下:

现金收取类

using System;namespace Strategy{//现金收取类public class CashContext{//收费方式private CashSuper cashSuper;public CashContext (CashSuper cashSuper){this.cashSuper = cashSuper;}//获取应付现金结果public double GetResult(double money){return cashSuper.AcceptCash(money);}}}
4.客户端代码,代码如下:

客户端代码

using System;namespace Strategy{class MainClass{public static void Main (string[] args){//测试 单价200 数量3CashContext cashContext = null;double totalPrices = 0;//正常收费cashContext = new CashContext (new CashNormal ());totalPrices = cashContext.GetResult (200 * 3);Console.WriteLine (totalPrices);//满300返100cashContext=new CashContext(new CashReturn("300","100"));totalPrices = cashContext.GetResult (200 * 3);Console.WriteLine (totalPrices);//打8折cashContext=new CashContext(new CashRebate("0.8"));totalPrices = cashContext.GetResult (200 * 3);Console.WriteLine (totalPrices);}}}

运行结果


UML图


源码下载地址:https://gitee.com/ZhaoYongshuang/DesignPattern.git
原创粉丝点击