策略模式
概念
策略模式是指有一定行动内容的相对稳定的策略名称。策略模式在古代中又称“计策”,简称“计”,如《汉书·高帝纪上》:“汉王从其计”。这里的“计”指的就是计谋、策略。策略模式具有相对稳定的形式,如“避实就虚”、“出奇制胜”等。一定的策略模式,既可应用于战略决策,也可应用于战术决策;既可实施于大系统的全局性行动,也可实施于大系统的局部性行动。
graph TD
A[策略接口]
B[具体策略A]
C[具体策略B]
D[具体策略C]
A--实现-->B
A--实现-->C
A--实现-->D
graph LR
B[具体业务类]
A[策略接口]
C[业务方法]
A--组合具体的实现策略 子类-->B
B--调用业务方法-->C
C--调用策略接口中的具体实现策略-->A
- 用王者上分来举例
/**
* @author : mengshuo
* @Description : 上分策略接口
*/
public interface UpStarStrategy {
/**
* 上分策略 提供默认实现
*/
default void upStar() {
System.out.println("自己打?不充钱?50连跪!");
}
}
/**
* @author : mengshuo
* @Description : 人民币上分策略
*/
public class RMBUpStar implements UpStarStrategy {
@Override
public void upStar() {
System.out.println("充钱使你变强,一百连胜一路上王者!");
}
}
/**
* @author : mengshuo
* @Description : 代练上分策略
*/
public class ReplaceUpStar implements UpStarStrategy {
@Override
public void upStar() {
System.out.println("代练上分策略,¥20 一颗star,代练把号盗了跑路了。");
}
}
/**
* @author : mengshuo
* @Description : 请演员上分策略
*/
public class PerformerUpStar implements UpStarStrategy {
@Override
public void upStar() {
System.out.println("请演员上分策略,演的漂亮加鸡腿,20连胜!");
}
}
/**
* @author : mengshuo
* @Description : 打游戏类 业务类
*/
public class PlayGame {
private UpStarStrategy upStarStrategy;
public PlayGame(UpStarStrategy upStarStrategy){
this.upStarStrategy = upStarStrategy;
}
/**
* 打游戏方法
*/
public void goUpStar(){
upStarStrategy.upStar();
}
}
/**
* @author : mengshuo
* @Description :
*/
public class Test {
public static void main(String[] args) {
//人民币上分策略
new PlayGame(new RMBUpStar()).goUpStar();
//请演员上分
new PlayGame(new PerformerUpStar()).goUpStar();
//请代练上分
new PlayGame(new ReplaceUpStar()).goUpStar();
}
}
// 结果:
// 充钱使你变强,一百连胜一路上王者!
// 请演员上分策略,演的漂亮加鸡腿,20连胜!
// 代练上分策略,¥20 一颗star,代练把号盗了跑路了。
通过组合不同的策略实现了不同的业务