case statements in Java

This question already has an answer here:

  • Converting many 'if else' statements to a cleaner approach 7 answers

  • One of the solution is to use polymorphism to handle triggers differently. For instance, you could declare the Trigger interface and have several implementations. In this case, when you need a new trigger type, you just implement this interface and don't touch the existing code:

    public interface Trigger {
        TriggerResultInterface execute(TriggerEventHelper eventHelper);
    }
    
    public class MetaTrigger implements Trigger {
        @Override
        TriggerResultInterface execute(TriggerEventHelper eventHelper) {
            // do meta trigger work here
        }
    }
    
    public class DataTrigger implements Trigger {
        @Override
        TriggerResultInterface execute(TriggerEventHelper eventHelper) {
            // do data trigger work here
        }
    }
    
    // ...
    
    public TriggerResultInterface executeTriggerJob(TriggerEventHelper eventHelper) {
        eventHelper.getTrigger().execute(eventHelper);
    }
    

    In this case it will be impossible to add a new trigger type and not implement its behaviour.

    If you need a default implementation, you can use a base class instead of the interface (in Java 8 you can add a default implementation right into the interface).

    链接地址: http://www.djcxy.com/p/35728.html

    上一篇: 找到一个不可简化的部分

    下一篇: Java中的case语句