这个问题类似于单例,但我需要创建一个只能允许'n'个对象的类,下面是我的代码
public class MSInt {
private static MSInt instance = null;
private static int count = 0;
private MSInt()
{
}
public static MSInt getInstance()
{
if(count < 5){
instance = new MSInt();
count++;
return instance;
}
else
{
return null;
}
}
}
这是可行的,但我正在考虑比这更好的解决方案(如果有的话)。
最佳答案
我认为这样做会更简洁。你不需要任何柜台。 它看起来也不错。
import java.util.ArrayList;
public class MSInt {
private static int MAX_OBJS = 10;
private static ArrayList<MSInt> instances = new ArrayList<MSInt>(MAX_OBJS);
private MSInt() {}
public static MSInt mkInstance() {
if(instances.size() < MAX_OBJS){
MSInt obj = new MSInt();
instances.add(obj);
return obj;
} else {
return null;
}
}
public static ArrayList<MSInt> getInstances() {
return instances;
}
}
关于java - 允许仅创建 'n' 个对象的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22447839/