假设使用场景:有几只宠物,猫跟狗等,要求他们做各种动作,比如叫,跑等,但是作为宠物这些都是相同的动作,只是猫,狗具体的表现不同,比如猫叫是喵,狗叫是汪
1.创建基础策略接口PetStrategy
java">public interface PetStrategy {//类型 cat-猫,dog-狗String getType();//执行动作 1 - 叫barkString bark();//执行动作 2 - 跑RUN 带参数例子String run(String name);
}
2.创建实现PetStrategy接口的猫CatStrategy跟狗DogStrategy用于实现具体的表现
注意加上@Service
java">//猫实现类
@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进来进行分配对应的策略
java">public interface PetStrategyHandler {//宠物叫行为String bark(String type);//宠物跑行为-带入参String run(String type,String name);
}
4.创建入口配置类,接收入口传来的type,用于实际分配不同的策略,类似工厂
java">@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测试
java">@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的好处不是百分百的,具体看实现要求吧,各有优缺点