策略细燎、工廠模式融合 InitializingBean
策略缝呕、工廠模式分別是什么
策略模式
策略模式是將不同的算法封裝成一個對象澳窑,這些不同的算法從一個抽象類或者一個接口中派生出來,客戶端持有一個抽象的策略的引用岳颇,這樣客戶端就能動態(tài)的切換不同的策略
工廠模式
工廠模式又分為簡單工廠和抽象工廠和工廠模式 照捡,這些工廠是為了創(chuàng)建對象而出現的,工廠模式創(chuàng)建不同的單個對象话侧,而抽象工廠是為了創(chuàng)建不同的一些列的對象或者操作
策略+工廠解決的痛點是什么
結合工廠模式通過不同的類型栗精,生產不同的對象和策略模式根據不同的對象,執(zhí)行相同方法內的不同行為瞻鹏,來消滅大量的 if else 或 switch case ...悲立,增強代碼的可擴展性,便于代碼質量維護
上代碼
代碼基礎:springboot 2.3.2
這里以 Animal 為策略的接口新博,Cat薪夕、Dog為策略具體的實現
public interface Animal {
void eat(String str);
}
/**
* @Author charmsongo
* @Create 2020/8/6 22:22
* @Description 實現 InitializingBean ,便于 spring 容器時赫悄,初始化一次 afterPropertiesSet
* 在 afterPropertiesSet 方法中把當前策略具體實現類注冊到策略中維護的 map 中
*/
@Component
public class Cat implements Animal, InitializingBean {
private static final Logger logger = LoggerFactory.getLogger(Cat.class);
@Override
public void eat(String str) {
logger.info("cat eat yu, {}", str);
}
/**
* 注冊到策略模式維護的集合中
* @throws Exception
*/
@Override
public void afterPropertiesSet() throws Exception {
AnimalContext.registerService(AnimalEnum.CAT.getCode(),this);
}
}
/**
* @Author charmsongo
* @Create 2020/8/6 22:24
* @Description 實現 InitializingBean 原献,便于 spring 容器時馏慨,初始化一次 afterPropertiesSet
* 在 afterPropertiesSet 方法中把當前策略具體實現類注冊到策略中維護的 map 中
*/
@Component
public class Dog implements Animal, InitializingBean {
private static final Logger logger = LoggerFactory.getLogger(Dog.class);
@Override
public void eat(String str) {
logger.info("dog eat gutou, {}", str);
}
/**
* 注冊到策略模式維護的集合中
* @throws Exception
*/
@Override
public void afterPropertiesSet() throws Exception {
AnimalContext.registerService(AnimalEnum.DOG.getCode(),this);
}
}
這里用枚舉來作為 map 的 key,此處直接使用姑隅,不用過多關注
public enum AnimalEnum {
CAT("01", "cat","貓"),
DOG("02", "dog","狗");
private String code;
private String shortCode;
private String msg;
AnimalEnum(String code, String shortCode, String msg) {
this.code = code;
this.shortCode = shortCode;
this.msg = msg;
}
public String getShortCode() {
return shortCode;
}
public void setShortCode(String shortCode) {
this.shortCode = shortCode;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
@Override
public String toString() {
return "AnimalEnum{" +
"code='" + code + '\'' +
", shortCode='" + shortCode + '\'' +
", msg='" + msg + '\'' +
'}';
}
public static boolean isValid(String code) {
for (AnimalEnum value : AnimalEnum.values()) {
if (value.getCode().equals(code)) {
return true;
}
}
return false;
}
}
策略+工廠模式具體的操作
/**
* @Author charmsongo
* @Create 2020/8/6 22:28
* @Description 策略+工廠
*/
public class AnimalContext {
private static final Logger logger = LoggerFactory.getLogger(AnimalContext.class);
private static Map<String, Animal> animalMap = new HashMap<String, Animal>();
private Animal animal;
public AnimalContext(String type) throws Exception {
//此處判空写隶,沒有可以拋異常
if (StringUtils.isEmpty(type) || !animalMap.containsKey(type)) {
logger.error("type is error.");
throw new Exception("type is error.");
}
animal = animalMap.get(type);
}
/**
* 策略 eat 方法
* @param str
*/
public void eat(String str) {
animal.eat(str);
}
/**
* 策略注冊方法
* @param type
* @param animal
*/
public static void registerService(String type, Animal animal) {
animalMap.put(type, animal);
}
}
測試
咱們 web 應用一般都是以服務的方式使用的,這里也以服務的方式測試
新加一個 Controller 和 Request
@RestController
public class StrategyController {
/**
* http://localhost:8080/hello?code=01
* @param animalRequest
*/
@GetMapping("/hello")
public void hello(AnimalRequest animalRequest) {
try {
AnimalContext animalContext = new AnimalContext(animalRequest.getCode());
animalContext.eat("哈哈");
animalContext.run("喜喜");
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class AnimalRequest implements Serializable {
private static final long serialVersionUID = 3784925575397162170L;
private String code;
// 省去 set讲仰、get慕趴、toString 方法
}
啟動 SpringBoot 工程的 Application 主類
然后查看 IDE 控制臺,出現 cat eat yu, 哈哈 即為成功鄙陡!
2020-10-13 22:38:28.712 INFO 12584 --- [nio-8080-exec-2] cn.songo.strategydemo.service.impl.Cat : cat eat yu, 哈哈
代碼詳情可參考源碼冕房,github:https://github.com/charmsongo/songo-code-samples/tree/master/strategydemo
如果有哪些不對的地方煩請指認,先行感謝