基本概念
策略模式指对象有某个行为,但在不同场景中,该对象有不同的实现算法。
应用场景列举
同一类型问题有不同处理方式(如计算器功能中的加减乘除,都是算法,但按下加号按钮的时候就要对数字进行加法运算,按下减号按钮的时候就要对数字进行减法运算),未来可能还会有其他的处理方式(如电商网站促销活动,中秋节时某件商品满100减20,满200减50,会员打八折,而在双十一,则前100位下单打七折,前500位打八折等)。
实现
public interface Strategy {
public void algorithm();
}
public class StrategyA {
public void algorithm() {
System.out.println("策略A");
}
}
public class StrategyB {
public void algorithm() {
System.out.println("策略B");
}
}
public class Context {
private Strategy strategy;
public Context(Strategy strategy){
this.strategy = strategy;
}
public int algorithm(){
return strategy.algorithm();
}
}
public class Client {
public static void main(String[] args) {
Context context = new Context(new StrategyA());
context.algorithm();
Context context = new Context(new StrategyB());
context.algorithm();
}
}
举例
使用策略模式实现简单的计算功能。
public interface Strategy {
public int calculate (int num1, int num2);
}
public class Addition implements Strategy {
@Override
public int calculate (int num1, int num2) {
return num1 + num2;
}
}
public class Subtraction implements Strategy {
@Override
public int calculate (int num1, int num2) {
return num1 - num2;
}
}
public class Context {
private Strategy strategy;
public Context (String mark){
switch (mark) {
case "+":
strategy = new Addition();
break;
case "-":
strategy = new Subtraction();
break;
default:
break;
}
}
public int calculate (int num1, int num2){
return strategy.calculate (num1, num2);
}
}
public class Client {
public static void main(String[] args) {
Context context = new Context("+");
System.out.println(context.calculate(1, 2))
}
}