effective 2

用枚举代替单例模式

高效而且安全


public enum Singleton {
    SINGLETON;

    public String say(){
        return "hello";
    }

    public static void main(String[] args) {
       String s = SINGLETON.say();
        System.out.println(s);
    }

}

用枚举代理int常量

清晰而且安全

public class Demo01 {

    public static void main(String[] args) {
        System.out.println(APPLE1.getAge());
    }

}

class Fruit{
    public static final int APPLE1 = 1;
    public static final int APPLE2 = 2;
    public static final int PEAR1 = 1;
    public static final int PEAR2 = 2;

}

enum Apple {
    APPLE1(1), APPLE2(2);
    private int age;

    public int getAge() {
        return age;
    }

    private Apple(int age) {
        this.age = age;
    }
}

enum Pear {
    PEAR1(1), PEAR2(2);
    private int age;

    public int getAge() {
        return age;
    }

    private Pear(int age) {
        this.age = age;
    }
}

用枚举代替各种状态

清晰,高效,安全

public enum EntryStatus implements DescEnum {
    INIT(0,"初始"),
    VALIDATED(1, "已生效"),
    NOTPASSED(2,"审核未通过"),
    ;
    private int code;
    private String desc;

    EntryStatus(int status,String desc) {
        this.code = status;
        this.desc = desc;
    }

    @Override
    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

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

    public void setDesc(String desc) {
        this.desc = desc;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值