马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
这个场景放到我们设计模式中就是叫有上限的多例模式(没上限的多例模式太容易了,和你直接 new 一
个对象没啥差别,以下是实现的代码:
import java.util.ArrayList;
import java.util.Random;
class Emperor
{
private static int maxNumOfEmperor = 2;
private static ArrayList emperorInfoLIst = new ArrayList(maxNumOfEmperor);
private static ArrayList emperorList = new ArrayList(maxNumOfEmperor);
private static int countNUmOfEmperor = 0;
static
{
for(int i=0; i < maxNumOfEmperor; i++)
{
emperorList.add(new Emperor("皇" + (i+1) + "帝"));
}
}
//就这么多啦! 不允许再次new一个对象出来
private Emperor(){}
private Emperor(String info)
{
emperorInfoLIst.add(info);
}
public static Emperor getInstance()
{
Random random = new Random();
countNUmOfEmperor = random.nextInt(maxNumOfEmperor); //随机产生一个数字
return (Emperor)emperorList.get(countNUmOfEmperor);
}
//皇帝叫什么名字
public static void emperorINfo()
{
System.out.println(emperorList.get(countNUmOfEmperor));
}
}
public class ManySingle
{
public static void main(String args[])
{
int ministerNum = 10; //10个大臣
for(int i=0; i < ministerNum; i++)
{
Emperor emperor = Emperor.getInstance();
System.out.print("第"+(i+1) + "个大臣参拜的是:");
emperor.emperorINfo();
}
}
}
|