最近这段时间,想给大家分享一下设计模式的一些用法以及在项目中怎么运用。
设计模式是软件设计中常见问题的典型解决方案。 它们就像能根据需求进行调整的预制蓝图, 可用于解决代码中反复出现的设计问题。
今天就拿其中一个问题来分析,使用策略模式来解决问题,没有了解过策略模式或者长时间不用已经忘了策略模式的小伙伴先来简单了解一下策略模式吧。
策略模式是一种行为型模式,它将对象和行为分开,将行为定义为 一个行为接口 和 具体行为的实现。策略模式最大的特点是行为的变化,行为之间可以相互替换。每个if判断都可以理解为就是一个策略。本模式使得算法可独立于使用它的用户而变化。
简单理解就是,针对不同的场景,使用不同的策略进行处理。
生活中比较常见的应用模式有:
场景:最近太热了,想要降降温,有什么办法呢
首先,定义一个降温策略的接口
public interface CoolingStrategy { /** * 处理方式 */ void handle(); }
定义3种降温策略;实现策略接口
public class IceCoolingStrategy implements CoolingStrategy { @Override public void handle() { System.out.println("使用冰块降温"); } }
public class FanCoolingStrategy implements CoolingStrategy { @Override public void handle() { System.out.println("使用风扇降温"); } }
public class AirConditionerCoolingStrategy implements CoolingStrategy { @Override public void handle() { System.out.println("使用空调降温"); } }
定义一个降温策略的上下文
public class CoolingStrategyContext { private final CoolingStrategy strategy; public CoolingStrategyContext(CoolingStrategy strategy) { this.strategy = strategy; } public void coolingHandle() { strategy.handle(); } }
测试
public class Main { public static void main(String[] args) { CoolingStrategyContext context = new CoolingStrategyContext(new FanCoolingStrategy()); context.coolingHandle(); context = new CoolingStrategyContext(new AirConditionerCoolingStrategy()); context.coolingHandle(); context = new CoolingStrategyContext(new IceCoolingStrategy()); context.coolingHandle(); } }
运行结果:
使用风扇降温
使用空调降温
使用冰块降温