1.策略(Strategy)模式的定义
策略模式的用意是针对一组算法,将每一个算法封装到具有共同接口的独立类中,从而使得它们可以相互替换。策略模式使得算法可以在不影响到客户端的情况下发生变化。
2.策略模式的主要优点
其主要缺点
3.策略模式的主要角色
4.策略模式的结构图
5.策略模式的实现,以购买车为例
package com.lw.designpattern.strategy; /** * @Classname CarStrategy * @Description 汽车策略接口 * @Author lw * @Date 2019-12-25 12:43 */ public interface CarStrategy { public void buyCar(); }
package com.lw.designpattern.strategy; /** * @Classname BcCar * @Description 奔驰车具体策略类 * @Author lw * @Date 2019-12-25 12:45 */ public class BcCar implements CarStrategy { @Override public void buyCar() { System.out.println("欢迎购买奔驰E300L。。。。。。"); } }
package com.lw.designpattern.strategy; /** * @Classname BmwCar * @Description 宝马车具体策略类 * @Author lw * @Date 2019-12-25 12:46 */ public class BmwCar implements CarStrategy { @Override public void buyCar() { System.out.println("欢迎购买宝马530Li。。。。。。"); } }
package com.lw.designpattern.strategy; /** * @Classname AudiCar * @Description 奥迪车具体策略类 * @Author lw * @Date 2019-12-25 12:46 */ public class AudiCar implements CarStrategy { @Override public void buyCar() { System.out.println("欢迎购买奥迪A6L。。。。。。"); } }
package com.lw.designpattern.strategy; /** * @Classname CarContext * @Description 汽车环境类 * @Author lw * @Date 2019-12-25 12:49 */ public class CarContext { private CarStrategy carStrategy; public CarContext(CarStrategy carStrategy){ this.carStrategy = carStrategy; } public void buyCarStrategy(){ carStrategy.buyCar(); } }
/** * 策略模式 */ @Test public void testStrategy(){ // 宝马车 CarContext bmwCarContext1 = new CarContext(new BmwCar()); bmwCarContext1.buyCarStrategy(); // 奔驰车 CarContext bcCarContext = new CarContext(new BcCar()); bcCarContext.buyCarStrategy(); // 奥迪车 CarContext audiCarContext = new CarContext(new AudiCar()); audiCarContext.buyCarStrategy(); }
打印结果
6.策略模式的应用场景
原文:https://www.cnblogs.com/lwcode6/p/12096091.html