用枚举实现单例,方法简单、安全。值得学习
enum Singleton {
RED(255, 0, 0), GREEN(0, 255, 0), BLUE(0, 0, 255);
// 构造枚举值
Singleton(int rv, int gv, int bv) {
this.redValue = rv;
this.greenValue = gv;
this.blueValue = bv;
}
// 自定义数据域,private为了封装。
private int redValue;
private int greenValue;
private int blueValue;
public int getRedValue() {
return redValue;
}
public void setRedValue(int redValue) {
this.redValue = redValue;
}
public int getGreenValue() {
return greenValue;
}
public void setGreenValue(int greenValue) {
this.greenValue = greenValue;
}
public int getBlueValue() {
return blueValue;
}
public void setBlueValue(int blueValue) {
this.blueValue = blueValue;
}
}
public class Demo {
public static void main(String[] args) {
System.out.println(Singleton.RED.getRedValue());
}
}