第 34 条:用Enum代替int常量

2021-05-16  本文已影响0人  综合楼
用Enum代替int常量.jpeg
public enum Planet {
    MERCURY(3.302e+23, 2.439e6),
    VENUS(4.869e+24, 6.052e6),
    EARTH(5.975e+24, 6.378e6),
    MARS(6.419e+23, 3.393e6),
    JUPITER(1.899e+27, 7.149e7),
    SATURN(5.685e+26, 6.027e7),
    URANUS(8.683e+25, 2.556e7),
    NEPTUNE(1.024e+26, 2.477e7);
    private final double mass;
    private final double radius;
    private final double surfaceGravity;
    
    private static final double G = 6.67300e-11;
    
    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
        surfaceGravity = G * mass / (radius * radius);
    }
    public double mass() {
        return mass;
    }

    public double radius() {
        return radius;
    }

    public double surfaceGravity() {
        return surfaceGravity;
    }
    public double surfaceWeight(double mass) {//F=ma
        return mass * surfaceGravity;
    }

}

import java.util.HashMap;
import java.util.Map;

public enum Operation {
    PLUS("+") {double apply(double x, double y) {return x + y;}},
    MINUS("-") {double apply(double x, double y) {return x - y;}},
    TIMES("*") {double apply(double x, double y) {return x - y;}},
    DIVIDE("/") {double apply(double x, double y) {return x - y;}};
    private final String symbol;
    Operation(String symbol) {
        this.symbol = symbol;
    }
    public String toString() {
        return symbol;
    }
    abstract double apply(double x, double y);

    private static final Map<String, Operation> stringToEnum = new HashMap<String, Operation>();
    static {
        for(Operation op : values())
            stringToEnum.put(op.toString(), op);
    }
    public static Operation fromString(String symbol) { return stringToEnum.get(symbol); }
}
enum PayrollDay {
    MONDAY(PayType.WEEKDAY),
    THESDAY(PayType.WEEKDAY),
    WEDNESDAY(PayType.WEEKDAY),
    THURSDAY(PayType.WEEKDAY),
    FRIDAY(PayType.WEEKDAY),
    SATURDAY(PayType.WEEKEND),
    SUNDAY(PayType.WEEKEND);

    private final PayType payType;
    PayrollDay(PayType payType) {
        this.payType = payType;
    }
    double pay(double hoursWorked, double payRate) {
        return payType.pay(hoursWorked, payRate);
    }

    private enum PayType {
        WEEKDAY {
            double overtimePay(double hours, double payRate) {
                return hours <= HOURS_PER_SHIFT ? 0 :
                    (hours - HOURS_PER_SHIFT) * payRate * 2;
            }
        },
        WEEKEND {
            double overtimePay(double hours, double payRate) {
                return hours * payRate / 2;
            }
        };
        private final static int HOURS_PER_SHIFT = 8;
        abstract double overtimePay(double hours, double Rate);
        double pay(double hoursWorked, double payRate) {
            double basePay = hoursWorked * payRate;
            return basePay + overtimePay(hoursWorked, payRate);
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读