class Color {
private String color;
//在static区就构造好对象
private static final Color RED = new Color("红色");
private static final Color GREEN = new Color("绿色");
private static final Color BLUE = new Color("蓝色");
private Color(String color) {
this.color = color;
}
public String getColor() {
return this.color;
}
//通过switch,来选择用哪一个对象
public static Color getColor(int ch) {
switch (ch) {
case 0:
return RED;
case 1:
return GREEN;
case 2:
return BLUE;
default:
return null;
}
}
}
public class testSingleton {
public static void main(String[] args) {
Color color = Color.getColor(1);
System.out.println(color.getColor());
}
}
【设计模式练习】多例设计
最新推荐文章于 2022-01-30 15:18:25 发布