前言
先來看張經典的啊都給神圖,感受下大量if-else的“魅力”
有時候業務上的拖拉可能要求我去寫出如上的多層if-else嵌套代碼,如果你碰上了一個對團隊成員要求相對比較嚴格的主管的話,那麼恭喜你,死定了……脾氣比較爆的大佬可能直接就跟你說要麼解決上面問題,要麼收拾包袱滾蛋了。
那上述代碼能否用設計模式相關解決呢,答案是:YES,可以用策略模式+工廠模式。
限於本文篇幅,上述的兩種模式這邊就不詳細介紹了,不懂的可以直接百度,本篇博文簡單粗暴,會以最暴力的代碼來解決問題。
原始代碼
public class Coffee {
public int getPrice(int type){
if(type==1){
System.out.println("卡布奇諾");
return 22;
}
if(type==2){
System.out.println("拿鐵");
return 25;
}
if(type==3){
System.out.println("美咖");
return 20;
}
return 21;
}
}
改進後的代碼
策略模式
分別定義這幾個咖啡
public interface Coffee {
int getPrice();
}
public class Cappuccino implements Coffee {
@Override
public int getPrice() {
return 22;
}
}
public class AmericanoCafe implements Coffee {
@Override
public int getPrice() {
return 20;
}
}
public class Latte implements Coffee {
@Override
public int getPrice() {
return 25;
}
}
那就可以根據type來new相應對象了,但實質還沒有解決上述多if問題。
工廠模式
public class CoffeeFactory {
private static Map<Integer,Coffee> coffeeMap=new HashMap<>();
public static Coffee buildCoffee(int type){
return coffeeMap.get(type);
}
public static void register(int type,Coffee coffee){
coffeeMap.put(type,coffee);
}
}
改進後的策略
此處會發現,每個具體的Coffee必須在初始化的時候將自身註冊到這個對應的coffeeMap中,否則在buildCoffee的時候會返回null,那該如何修改呢?看下面代碼
@Component
public class Cappuccino implements Coffee, InitializingBean {
@Override
public int getPrice() {
return 22;
}
@Override
public void afterPropertiesSet() throws Exception {
CoffeeFactory.register(1,this);
}
}
@Component
public class AmericanoCafe implements Coffee, InitializingBean {
@Override
public int getPrice() {
return 20;
}
@Override
public void afterPropertiesSet() throws Exception {
CoffeeFactory.register(2,this);
}
}
@Component
public class Latte implements Coffee, InitializingBean {
@Override
public int getPrice() {
return 25;
}
@Override
public void afterPropertiesSet() throws Exception {
CoffeeFactory.register(3,this);
}
}
之所以要實現InitializingBean接口是爲了Spring初始化的時候,創建對應的Coffee Bean的時候將其註冊到工廠map中