设计模式-限制性多例模式

import java.util.Random;import java.util.Vector;/*luozhonghua 2014-9-20*/public class moreOfSingleton {private static int maxNumberOfSingleton=2;//多单例数量private static Vector nameList=new Vector(); //多单例名称//多单例实例,注意线程安全private static Vector moreOfSingletonList=new Vector();private static int count=0;//多单例序号,显示区别//初始化static{for(int i=0;i<maxNumberOfSingleton;i++){moreOfSingletonList.add(new moreOfSingleton("多单例"+(i+1)));}}private moreOfSingleton(){};private moreOfSingleton(String name){nameList.add(name);}//随机获得一个多单例对象public static moreOfSingleton getInstance(){Random random=new Random();count=random.nextInt(maxNumberOfSingleton);return moreOfSingletonList.get(count);}//打印随机多单例public static void toPrint(){ System.out.println(nameList.get(count));} //测试多单例访问public static void main(String [] args){ for(int i=0;i<5;i++){ System.out.print((i+1)+":"); moreOfSingleton.getInstance().toPrint(); } }}
posted @ 2014-09-20 22:26  172257861  阅读(85)  评论(0编辑  收藏  举报