定义
策略模式注重的是行为的灵活切换,以便应对不同情况时,使系统功能能够得到灵活的扩展。
犹记得小时候,玩过的掌上游戏机,里面有那时候非常流行的俄罗斯方块,遗憾的是也仅仅只有这么一个游戏,无法体验到各种不同游戏带给我们的童年欢乐。
代码实现
俄罗斯方块游戏机,只能玩这一块游戏
public class Tetris {
public void play() {
System.out.println("俄罗斯方块陪你度过欢乐童年。");
}
}
优化
定义一个游戏接口,添加一个play()抽象方法,以便其子类实现
public interface Game {
void play();
}
定义一个游戏机类,可以连接各种不同的游戏子类
public class PlayStation {
private Game game;
public void setGame(Game game) {
this.game = game;
}
public void play() {
this.game.play();
}
}
现在我们的游戏机可以根据需要,选择玩耍不同的游戏。显而易见,重构后的游戏机类变得非常灵活,不管我们想玩哪种游戏,我们只需注入对应的游戏子类即可。我们不必再对系统做修改即可实现功能的无限扩展。
public class Client {
public static void main(String[] args) {
PlayStation playStation = new PlayStation();
playStation.setGame(new Mario());
playStation.play();
// 超级玛丽陪你度过欢乐童年
playStation.setGame(new TankWar());
playStation.play();
// 坦克大战陪你度过欢乐同年
}
}
以上就是策略模式的所有内容,我将持续更新设计模式,欢迎大家一起交流😁