利用枚举管理事务逻辑

一个利用枚举进行管理用户逻辑的例子,这里一共定义了两个逻辑,并且提供了一个根据逻辑名返回对象的静态函数:

package Utility.ext.testconnect;

public enum BizRules {
    PIP_YA(
            "[RULE] PIP_YA: from 1 Jan to 20 Mar, return this year otherwise return next year"),

    BILL_B4_OCT(
            "[RULE] BILL_B4_OCT: from Jan to Sep return this year's bill value, from Oct to Dec return sum of this year & next year's bill value");

    // desc is used for easy debug
    private String desc;

    private BizRules(String desc) {
        this.desc = desc;
    }

    @Override
    public String toString() {
        return getDesc();
    }

    // find rule by rule name
    public static BizRules findRule(String rule) {
        for (BizRules biz : BizRules.values()) {
            if (biz.name().equalsIgnoreCase(rule)) {
                return biz;
            }
        }
        return null;
    }

    public String getDesc() {
        return desc;
    }
}

下面的代码提供了对各种逻辑名的具体实现:

package Utility.ext.testconnect;

import java.util.Calendar;

public class BizRuleBean {

    private int option;
    private String desc;

    public BizRuleBean(String rule) {
        this.option = runRule(rule);
    }

    private int runRule(String rule) {
        BizRules biz = BizRules.findRule(rule);
        if (biz == null) {
            return -1;
        }

        desc = biz.getDesc();

        switch (biz) {
        case PIP_YA:
            return pipYA();
        case BILL_B4_OCT:
            return billB4OCT();
        }
        return -1;
    }

    // see desc of BizRules.PIP_YA
    private int pipYA() {
        Calendar cal = Calendar.getInstance();
        int month = cal.get(Calendar.MONTH) + 1;
        int day = cal.get(Calendar.DATE);
        if (month > 3) {
            return 1;
        } else if (month == 3) {
            if (day > 20) {
                return 1;
            } else {
                return 0;
            }
        } else {
            return 0;
        }
    }

    // see desc of BizRules.BILL_B4_OCT
    private int billB4OCT() {
        Calendar cal = Calendar.getInstance();
        int month = cal.get(Calendar.MONTH) + 1;
        if (month < 10) {
            return 0;
        } else {
            return 1;
        }
    }

    public int getOption() {
        return option;
    }

    public String getDesc() {
        return desc;
    }
}
原文地址:https://www.cnblogs.com/ryansunyu/p/4313154.html