java: create a lookup table using hashmap or some other java collection?

只愿长相守 提交于 2019-11-30 23:57:37

I would use a

Map<Criteria, Message> lookupTable;

where Criteria is a class you write (and override equals() and hashCode()), representing the criteria to choose a message.

Message is also a class you write, which encapsulates the actual message String but also provides you some functionality to set the variables.

With this solution you have to initialize the map once at the beginning of your program and can always use it like this:

Criteria criteria = ... // gather your criteria somehow
Message msg = lookupTable.getMessage(criteria);
// use your variable setting methods here
String message = msg.toString();

You could use an enum, assuming the list of messages is known at compile time. The advantages are that each message is now responsible for holding its condition, and the calling code will be much simpler.

public enum Message {

    MESSAGE1("Welcome") {
        @Override
        boolean isApplicable(long totalDays, int x, int y) {
            return totalDays < 7 && x < 20;
        }
    },
    MESSAGE2("Bye bye") {
        @Override
        boolean isApplicable(long totalDays, int x, int y) {
            return totalDays < 7 && x > 10 && y < 20;
        }
    };

    private String msg;

    Message(String msg) {
        this.msg = msg;
    }

    abstract boolean isApplicable(long totalDays, int x, int y);

    public static String lookupMessage(long totalDays, int x, int y) {
        for (Message m : Message.values()) {
            if (m.isApplicable(totalDays, x, y)) {
                return m.msg;
            }
        }
        throw new IllegalArgumentException();
    }
}

Now in your calling code, no more if / else if, just one line of code:

System.out.println(Message.lookupMessage(1, 2, 3));

Note 1: This is not as efficient as using a Map as the lookup is an O(n) operation, but because n is 100 or so it should not be a significant performance penalty. And it is more readable and maintainable than the solution proposed in the other answer.

Note 2: You could even put the conditions / messages in a flat file, read the file at runtime and use a scripting engine to eval each condition at runtime. It would be slightly slower (but we are talking about sub-milliseconds here) but would remove all the clutter from your code and put it in a configuration file.

If you have so many conditions, you cant avoid putting those conditions some where in the code. The advantages of using lookup table is 1)Easy to implement. 2)Flexible.If you want to change the value of some message in future, you can go to looktable class and change.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!