- 本质上与单例模式没有区别
class Color {
// 在类内部提供有若干个实例化对象,如果为了方便管理,也可以通过对象数组的形式定义;
private static final Color RED = new Color("红色");//实例化对象
private static final Color GREEN = new Color("绿色");
private static final Color BLUE = new Color("蓝色");
private String title;
private Color(String title){//构造方法私有化
this.title = title;
}
public static Color getInstance(String color){// 获取实例化对象
switch(color){
case "red":return RED;
case "green":return GREEN;
case "blue":return BLUE;
default:return null;
}
}
public String toString(){// 对象打印时候自动调用
return this.title;
}
}
public class JavaDemo {
public static void main(String args[]) {
Color c = Color.getInstance("green");
System.out.println(c);
}
}
标签:return,String,多例,Color,10.8,title,private,static,模式
From: https://www.cnblogs.com/pansidong/p/17519308.html