JAVA设计模式——策略模式

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

策略模式是一种定义一系列算法的方法,从概念上看,所有这些算法完成的都是相同的工作,只是实现不同,它可以以相同的方式调用所有的算法,减少了各种算法类与使用算法类之间的耦合。

策略模式的Strategy类层次定义了一系列的可供重用的算法或行为,继承有助于析取出这些算法中的公共功能。

策略模式就是用来封装算法的,在实践中,可以用它来封装几乎任何类型的规则,只要在分析过程中听到需要在不同时间应用不同的业务规则,就可以考虑使用策略模式处理这种变化的可能性。

策略模式结构图

一个接口,接口方法在其实现类中有不同的实现。

/**
* 策略模式接口
*/
public interface Strategy {
public double getMoney(double money);
}

/**
* 第一种方式,不打折
*/
public class FirstStrategy implements Strategy {
@Override
public double getMoney(double money) {
return money;
}
}

/**
* 第二种方式,打几折
*/
public class SecondStrategy implements Strategy {
private Integer num = 10;
public SecondStrategy() {
}
public SecondStrategy(Integer num) {
this.num = num;
}
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
@Override
public double getMoney(double money) {
return this.num*money*0.1;
}
}

/**
* 第三种方式,满一定金额减多少
*/
public class ThirdStrategy implements Strategy {
private Integer reach = 0;
private Integer reduce = 0;
public ThirdStrategy() {
}
public ThirdStrategy(Integer reach, Integer reduce) {
this.reach = reach;
this.reduce = reduce;
}
public Integer getReach() {
return reach;
}
public void setReach(Integer reach) {
this.reach = reach;
}
public Integer getReduce() {
return reduce;
}
public void setReduce(Integer reduce) {
this.reduce = reduce;
}
@Override
public double getMoney(double money) {
if (money > this.reach && this.reach != 0){
return money - Math.floor(money / this.reach) * this.reduce;
}
return money;
}
}

/**
* 调用策略
*/
public class CashContext {
private Strategy strategy;
public CashContext(String s,Integer num,Integer money){
switch (s){
case “1”: //不打折
this.strategy = new FirstStrategy();
break;
case “2”: //打折
this.strategy = new SecondStrategy(num);
break;
case “3”: //满减
this.strategy = new ThirdStrategy(num,money);
break;
}
}
public double getResult(double money){
return this.strategy.getMoney(money);
}
}

public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println(“请输入购买总金额”);
Double money = scanner.nextDouble();
System.out.println(“请输入打折方式”);
String strategy = scanner.next();
Double costMoney = 0.0;
switch (strategy){
case “1”:
costMoney = money;
break;
case “2”:
System.out.println(“请输入打几折”);
int num = scanner.nextInt();
costMoney = new CashContext(strategy,num,0).getResult(money);
break;
case “3”:
System.out.println(“请输入满减金额”);
int reach = scanner.nextInt();
System.out.println(“请输入优惠金额”);
int reduce = scanner.nextInt();
costMoney = new CashContext(strategy,reach,reduce).getResult(money);
break;
default:costMoney = money;
break;
}
System.out.println(“计算总价中,请稍后···”);
System.out.println(“花费总价为:” + costMoney);
scanner.close();
}
}

猜你喜欢

转载自blog.csdn.net/qq_36997245/article/details/81704086