java學習:用Map替代眾多的if-else


(20160329add)簡略地說:

if(A){

Ahandler.handle(a);

} else if (B){

Bhandler.handle(b);

} else if (C){

Chandler.handle(c);

}

可以改寫成:

//初始化map

Map map;

map.put(A,Ahandler);

map.put(B,Bhandler);

map.put(C,Chandler);

//處理

map.get(X).handle(x);

 

#2014.11.13#

問題情景:根據標簽對字符串做出相應的處理,輸入格式:{標簽}{目標字符串}

大寫化 String1
小寫化 String2
逆序 String3
....
functionN StringN
 
通常用if else的實現方式大致如下:
while(讀取行) {
將每一行的輸入拆分,然后存入String function,String str;
if ( function.equals("大寫化")){
//調用函數處理str
}else if ( function.equals("小寫化")){
//調用函數處理str
}else if(){
}
...
}
 
這樣寫很不痛快而且代碼難看,使用Map的映射能力可以解決這個問題,基本思路是使用Map將<處理標簽>和相應的<類>建立映射關系,這樣的話Map.get(<標簽>)就是那個類了,接下來調用方法即可解決Map.get(<標簽>).getResult(str);
 
實現方式如下:
首先定義一個接口
public interface Type {
    String getResult (String str);
}
 
接下來繼承這個接口實現各種功能類
public class functionA implements Type{
    @Override
    public String getResult ( String str ){
        //A函數的功能
    }
}
.....同樣的functionB,functionC ......
 
以上是一些准備工作,一開始的 if-else 部分轉化如下:
Map<String,Type> map= new HashMap<String,Type>();
        map.put("大寫化",new functionA());
        map.put("小寫化",new functionB());
        map.put("逆序", new functionC());
.......
while(讀取行){
將每一行的輸入拆分,然后存入String function,String str;
map.get( function ).getResult( str );
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM