Java learning: Replacing many if-else with maps

Source: Internet
Author: User

#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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.