![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8f6df7a92f2f53b17e1e3900e6f85a95.png)
多例类
import java.util.ArrayList;
import java.util.Random;
public 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));
}
}
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(emperorInfoList.get(countNumOfEmperor));
}
public static Emperor getInstance(Integer param) {
return (Emperor) emperorList.get(param);
}
}
客户端
public class Main {
public static void main(String[] args) {
int ministerNum = 10;
Emperor emperor = null;
for (int i=0; i< ministerNum; i++){
if (i < 3) {
emperor = Emperor.getInstance(1);
} else {
emperor = Emperor.getInstance();
}
System.out.print("第" +(i+1)+ "个大臣参拜的是:");
emperor.emperorInfo();
}
}
}
结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/c6016e8e6fe05ccdd7ab90226e55298e.png)