JAVA笔记 | 计谋模式+罗列Enum简单实现计谋模式(可直接套用)
本篇为更为简单的计谋模式应用,使用罗列来进行计谋分配上一篇(链接如下)更像是计谋+工厂模式来分配计谋
JAVA笔记 | 现实上用到的计谋模式(可直接套用)-CSDN博客
先创建计谋相干类
//策略类
public interface PetStrategy {
/**
* 执行动作- 跑RUN
*/
String run(String name);
}
//猫实现类
@Service
public class CatStrategy implements PetStrategy{
@Override
public String run(String name) {
return name + "猫跑了";
}
}
//狗实现类
@Service
public class DogStrategy implements PetStrategy{
@Override
public String run(String name) {
return name + "狗跑了";
}
} 新建计谋罗列
@Getter
public enum PetTypeEnum {
DOG("1", "DOG", new DogStrategy()),
CAT("2", "CAT", new CatStrategy());
private String code;
private String type;
private PetStrategy petStrategy;
PetTypeEnum(String code, String type,PetStrategy strategy) {
this.code = code;
this.type = type;
this.petStrategy = strategy;
}
//根据code获得枚举策略类型
public static PetTypeEnum getPetTypeEnum(String code){
PetTypeEnum type = Arrays.stream(PetTypeEnum.values())
.filter(a -> a.code.equals(code))
.findFirst()
.orElse(null);
if(null == type){
throw new IllegalArgumentException("未找到type");
}
return type;
}
} controller调用测试
https://i-blog.csdnimg.cn/direct/297b9a2a2c5d4b6f80241ff8857bcf71.png
https://i-blog.csdnimg.cn/direct/19272bcc898c4a1d84cfd222a062bb99.png
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页:
[1]