您的位置:首页 > 其它

一文让你读懂策略模式

2016-12-20 22:13 429 查看
首先从定义来看,
define:它定义了算法家族,分别封装起来,让他们之间相互的替换,使用此模式,不会影响到客户端的使用。

从一个简单的例子来说:
假如四六级考试中,考试委员会提出了一种优惠方案,连续报名3次考6级,将会优惠10元报名费和满350送20,满400送25,于是工程师连夜修改成绩登记系统,和交费系统,于是有了如下的代码:
public void ComputerMoney(User user , Score score){
if(user.get次数==3){
float money = money-10;
}
if(score>350 && score<400){
score=+50;
}
if(score>450){
score=+25;
}

}

但是因为第二年很多的考生通过这优惠条件考过了四六级,报名人数急剧减少,考委会连夜召开紧急会议商讨收费方案,终于决定连续报名5次才有优惠10元,满350送10满400送5.程序员连夜修改系统
public void ComputerMoney(User user , Score score){
if(user.get次数==5){
float money = money-10;
}
if(score>350 && score<400){
score=+10;
}
if(score>450){
score=+5;
}

}

假如考委会下次又需要改变策略,那么该怎么办呢?这时候就应该拥戴策略模式:

首先,我们定义一个策略的抽象类,他是所有策略的公共接口:

package com.hemin.starge;

public abstract class Strategy {
public abstract void AlgorithmInterface();
}


接下来需要写一个类,且继承Strategy , 封装好具体的算法和行为。
算法A
package com.hemin.starge;

public class ConcreateStrategyA extends Strategy {

@Override
public void AlgorithmInterface() {
System.out.println("A");

}

算法B

package com.hemin.starge;
public class ConcrateStrategyB extends Strategy {

@Override
public void AlgorithmInterface() {
System.out.println("B");
}

}


接下来写一个Context上下文类,使用具体算法来配置,从而调用一个策略

package com.hemin.starge;

public class Context {
Strategy strategy;
public Context(Strategy strategy){
this.strategy = strategy;
}
public void ContextInterface(){
strategy.AlgorithmInterface();
}

}


对于客户端,我们可以灵活的调用算法
package com.hemin.starge;

public class Test {
public static void main(String[] args) {
Context context = new Context(new ConcreateStrategyA());
context.ContextInterface();
Context context2 = new Context(new ConcrateStrategyB());
context2.ContextInterface();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: