自己开发中用到了策略模式,这样写不一定是最好的,但是满足了业务场景跟使用要求,做个笔记,下次有用到可以快速复习跟套用
假设使用场景:有几只宠物,猫跟狗等,要求他们做各种动作,比如叫,跑等,但是作为宠物这些都是相同的动作,只是猫,狗具体的表现不同,比如猫叫是喵,狗叫是汪
1.创建基础策略接口PetStrategy
public interface PetStrategy {//类型 cat-猫,dog-狗String getType();//执行动作 1 - 叫barkString bark();//执行动作 2 - 跑RUN 带参数例子String run(String name);
}
2.创建实现PetStrategy接口的猫CatStrategy跟狗DogStrategy用于实现具体的表现
注意加上@Service
//猫实现类
@Service
public class CatStrategy implements PetStrategy{@Overridepublic String getType() {return "cat";}@Overridepublic String bark() {return "猫叫喵喵喵";}@Overridepublic String run(String name) {return name + "猫跑了";}
}//狗实现类
@Service
public class DogStrategy implements PetStrategy{@Overridepublic String getType() {return "dog";}@Overridepublic String bark() {return "狗叫汪汪汪";}@Overridepublic String run(String name) {return name + "狗跑了";}
}
3.创建统一策略入口,即不同宠物类型type进来进行分配对应的策略
public interface PetStrategyHandler {//宠物叫行为String bark(String type);//宠物跑行为-带入参String run(String type,String name);
}
4.创建入口配置类,接收入口传来的type,用于实际分配不同的策略,类似工厂
@Configuration
public class PetStrategyConfig {@Beanpublic PetStrategyHandler petHandler(List<PetStrategy> strategies) {Map<String, PetStrategy> strategyMap = strategies.stream().collect(Collectors.toMap(PetStrategy::getType, item -> item));PetStrategyHandler handler = new PetStrategyHandler() {@Overridepublic String bark(String type) {return strategyMap.get(type).bark();}@Overridepublic String run(String type,String name) {return strategyMap.get(type).run(name);}};return handler;}
}
5.创建controller测试
@RestController
@RequestMapping("/pet")
public class PetController {@Resourceprivate PetStrategyHandler handler;@GetMapping("/bark/{type}")public String bark(@PathVariable String type){return this.handler.bark(type);}@GetMapping("/run/{type}")public String run(@PathVariable String type,@RequestParam String name){return this.handler.run(type,name);}
}
这样后续如果有新的动物,只需增加新的xxStrategy跟传对应type就好,策略模式替换if的好处不是百分百的,具体看实现要求吧,各有优缺点