#2014.11.13#
Problem Scenario: The string is processed according to the tag, input format: {tag} {target String}
Capitalization String1 lowercase String2 The reverse string3....functionn stringn typically implemented with if else is as follows: while (reading rows) {Splits the input of each row and then deposits a string Function,string str;if (Function.equals ("capitalization")) {//Call function to handle Str}else if ( function.equals ("lowercase")) {//Call function to process STR} else if () {} ...} This is very unpleasant and the code is ugly, using map mapping ability to solve this problem, the basic idea is to use the map < processing tags > and the corresponding < class > mapping relationship, so Map.get (< tag >) Is that class, the next call to the method can solve Map.get (< tag >). GetResult (str); is implemented as follows: first define an interface public interface Type { String GetResult (String str);} Next inherits this interface to implement various functional classes public class Functiona implements type{ @Override public String GetResult ( string str ) { //a functions } ..... The same functionb,functionc ...... above is some preparatory work, the first part of the If-else transformation is as follows:map<string,type> map= new hashmap<string, Type> (); Map.put ("Capitalization", New Functiona ()); map.put ("lowercase", new &NBSP;FUNCTIONB ()); map.put ("reverse", New functionc (); ... while (reading rows) {Splits the input of each row and then deposits the String function,string str;map.get (function). GetResult (str);}
Java learning: Replacing many if-else with a map