既然程序中可以存在单例设计,那么就可以存在多例设计。
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 name ; public static Color getInstance(int ch){ // 将instance传递到外部去 if(ch==0){ return RED ; } else if(ch==1){ return GREEN ; } else if(ch==2){ return BLUE ; } else { return null ; } } private Color(String name){ this.name = name ; } public void print(){ System.out.println("当前颜色:" + this.name) ; } }; public class Test{ public static void main(String args[]){ Color s1 = Color.getInstance(0) ; Color s2 = Color.getInstance(1) ; Color s3 = Color.getInstance(2) ; s1.print() ; s2.print() ; s3.print() ; } };