这个问题类似于单例模式,但我需要创建一个只能允许'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;
}
}
}
这种方法可以工作,但我认为如果有更好的解决方案会更好。
public synchronized static MSInt getInstance()
以避免竞争条件。 - wns349