Use Map and polymorphism to eliminate a large number of if or else if statements in java code

Too many if and else if statements in the code will cause trouble for code maintenance and reading. Generally, more than three ifs can be changed to switch, and more than ten can be changed to polymorphism or some design patterns. The following is my use of map and polymorphism To eliminate excessive if statements.

interface:

import java.util.Map;

public interface TableDataServer {

    Map<String,Object> getData(Map<String, Object> map);
}

Implementation interface:

public class Tdb1 implements TableDataServer {
    @Override
    public Map<String, Object> getData(Map<String, Object> map) {
    return null;
    }
}
public class Tdb2 implements TableDataServer {
    @Override
    public Map<String, Object> getData(Map<String, Object> map) {
    return null;
    }
}
public class Tdb3 implements TableDataServer {
    @Override
    public Map<String, Object> getData(Map<String, Object> map) {
    return null;
    }
}

 Entrance used:

 private static Map<String, TableDataServer> serverMap = new HashMap<>(8);

    //方法
    static {
        serverMap.put("Tdb1",new Tdb1());
        serverMap.put("Tdb2",new Tdb2());
        serverMap.put("Tdb3",new Tdb3());
    }


public static void main(String[] args) {
    String type = "Tdb1"
    TableDataServer tableDataServer = serverMap.get(type);
    tableDataServer.getData();

}

 

Guess you like

Origin blog.csdn.net/qq_36802726/article/details/103252109