策略模式
来源:互联网 发布:js判断鼠标滚动方向 编辑:程序博客网 时间:2024/06/06 04:16
策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。
策略模式由抽象策略类、具体策略类、环境角色三部分组成。抽象策略类通常由有一个抽象类或一个接口构成,在这个抽象类或接口中定义所有支持的算法的公共接口。具体策略类继承于抽象策略类,封装了具体的算法或行为。环境角色持有一个抽象策略类的引用,用来供客户端调用。
策略模式UML图:
应用场景:
1. 多个类只区别在表现行为不同,可以使用策略模式来动态的选择具体要执行的行为。
2. 在不同情况下需要使用不同的算法,即只要在不同时间内需要应用不同的业务规则,就可以考虑使用策略模式处理。
策略模式的优点:
1. 提供了一种替代继承的方法,既保持了继承的优点还比继承灵活,使得算法独立可以任意扩展。
2. 实现了高内聚弱耦合。
3. 避免类程序中使用多重条件转移语句,是系统更灵活更易扩展。
4. 对客户隐藏具体的行为,算法的具体实现完全独立。
缺点:
由于每个具体类都会产生一个新类,所以会增加系统维护的类的数量。
商场促销策略模式实现代码:
抽象策略类:
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace 策略模式{ abstract class CashSuper { public abstract double acceptCash(double money); }}具体策略类:
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace 策略模式{ class CashNormal:CashSuper { public override double acceptCash(double money) { //throw new NotImplementedException(); return money; } }}
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace 策略模式{ class CashReturn:CashSuper { private double moneyCondition=0.0d; private double moneyReturn=0.0d; public CashReturn(String moneyConditon,String moneyReturn) { this.moneyCondition = double.Parse(moneyConditon); this.moneyReturn = double.Parse(moneyReturn); } public override double acceptCash(double money) { double result=money; // throw new NotImplementedException(); if (money > moneyCondition) { result = money - Math.Floor(money / moneyCondition) * moneyReturn; } return result; } }}
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace 策略模式{ class CashRebate:CashSuper { private double moneyRebate = 1d; public CashRebate(String moneyRebate) { this.moneyRebate = double.Parse(moneyRebate); } public override double acceptCash(double money) { //throw new NotImplementedException(); return money * moneyRebate; } }}
环境角色Context类:
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace 策略模式{ class CashContext { private CashSuper cash; public CashContext(string type) { switch (type) { case "正常收费": cash = new CashNormal(); break; case "打八折": cash = new CashRebate("0.8"); break; case "满300返100": cash = new CashReturn("300","100"); break; } } public double GetResult(double money) { return cash.acceptCash(money); } }}
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- PHP 中文简易分词
- Redhat下配置iptables防火墙
- JAVA正则表达式简单总结
- MFC表格控件的简单使用
- C#线程篇---让你知道什么是线程(1)
- 策略模式
- 最近的状态好混乱
- jQuery调用WCF需要注意的一些问题
- addView(View, LayoutParams) is not supported in AdapterView异常
- 软件开发比较齐全的帮助文档
- jquery调WCF
- Java实现的几个常用排序算法详细解读
- 将Eclipse中的Web项目部署到Tomcat
- Documentum 中编号标识和type类型的对应关系表(基础)