设计模式——策略模式
策略模式
策略模式是什么呢,可以把策略看成算法,我们通过传递不同的key,从而拿到不同的算法,仔细想想,这不就是if-else吗
原先的if-else逻辑
public static String getGame(String gameName) { if ("Shield".equals(gameName)) { return "破壳梦_盾"; } else if ("Sword".equals(gameName)) { return "破壳梦_剑"; } else if ("Pearl".equals(gameName)) { return "明亮珍珠"; } else if ("Diamond".equals(gameName)) { return "晶灿钻石"; } return null; } public static void main(String[] args) { String gameName = getGame("Pearl"); System.out.println(gameName); }
运行结果
明亮珍珠
if-else不香吗,阅读方便,容易理解。但是呢,如果我们想要添加新的if逻辑,就不得不在getGame方法中添加判断逻辑,这有违背开闭原则。其次呢,如果代码是由多人维护,可能不是会很方便,那么,就可以使用策略模式的思想来解决这个问题。
我们可以首先定义一个顶层接口
public interface Game { String getGame(); }
然后实现各种不同的算法,这样当由新的算法加入时,只需要实现"顶层的算法",就可以,不断的扩展,非常符合开闭原则
public class Game_Diamond implements Game { @Override public String getGame() { return "晶灿钻石"; } }
public class Game_Pearl implements Game { @Override public String getGame() { return "明亮珍珠"; } }
public class Game_Shield implements Game { @Override public String getGame() { return "破壳梦_盾"; } }
public class Game_Sword implements Game { @Override public String getGame() { return "破壳梦_剑"; } }
有了算法,我们需要一个能够运用算法的工具
@Data
public class Game_Center {
private Game game;
public String getGame() {
if (game == null) {
return null;
}
return game.getGame();
}
}
最后,我们去运用这个工具
public static void main(String[] args) { Game_Center gameCenter = new Game_Center(); gameCenter.setGame(new Game_Sword()); System.out.println(gameCenter.getGame()); gameCenter.setGame(new Game_Shield()); System.out.println(gameCenter.getGame()); gameCenter.setGame(new Game_Pearl()); System.out.println(gameCenter.getGame()); gameCenter.setGame(new Game_Diamond()); System.out.println(gameCenter.getGame()); }
运行结果
破壳梦_剑 破壳梦_盾 明亮珍珠 晶灿钻石
懂了,策略模式的最终目的就是毛代码量,是解耦。那么,代价呢,古尔丹?
策略模式,需要我们知道自行知道需要使用那个算法,还需要知道这些算法之间到底有什么不同。如果你使用了策略模式,还需要进行if-else判断,那么可能就不适合使用策略模式。
本文来自博客园,作者:异世界阿伟,转载请注明原文链接:https://www.cnblogs.com/yusishi/p/15751115.html

浙公网安备 33010602011771号