多例设计模式是单例模式的拓展,单例模式是只保留一个类的实例化对象,而多例模式是定义了多个对象。是有限个数对象的。
public class ManyCases {
public static void main(String[] args) {
Color color = Color.getInstance("blue");
System.out.println(color.getTitle());
}
}
//多例设计模式
class Color{
private static final Color RED = new Color("red");
private static final Color BLUE = new Color("blue");
private static final Color GREEN= new Color("green");
private static final Color YELLOW = new Color("yellow");
private String title;
private Color(String title){
this.title = title;
}
public static Color getInstance(String title){
switch (title){
case "red":
return RED;
case "blue":
return BLUE;
case "green":
return GREEN;
case "yellow":
return YELLOW;
default:
return null;
}
}
public String getTitle(){
return title;
}
}
网友评论