如何在Java类中限制对象创建不超过3个?

您能给我一个我该怎么做的想法吗?

最佳答案

我们可以通过在Singleton设计模式中进行少量修改来限制特定类的Object的创建,如下所示:

public class LimitClass {

    private static LimitClass limInstance;
    public static int objCount = 0;

    private LimitClass(){
        objCount++;
    }

    public static synchronized LimitClass getLimInstance(){
        if(objCount < 3 ){
            limInstance = new LimitClass();
        }
        return limInstance;
    }
}

public class LimitObjectCreationTest {

    public static void main(String[] args) {

        LimitClass obj1 = LimitClass.getLimInstance();
        LimitClass obj2 = LimitClass.getLimInstance();
        LimitClass obj3 = LimitClass.getLimInstance();
        LimitClass obj4 = LimitClass.getLimInstance();
        LimitClass obj5 = LimitClass.getLimInstance();
        LimitClass obj6 = LimitClass.getLimInstance();

        System.out.println(obj1);
        System.out.println(obj2);

        System.out.println(obj3);
        System.out.println(obj4);
        System.out.println(obj5);
        System.out.println(obj6);
      }
}

上面代码的输出如下:
com.pack2.LimitClass@19821f
com.pack2.LimitClass@addbf1
com.pack2.LimitClass@42e816
com.pack2.LimitClass@42e816
com.pack2.LimitClass@42e816
com.pack2.LimitClass@42e816

创建了三个不同的对象后,它将一次又一次地重复相同的第三个对象。它不是在创建其他对象。

09-27 11:13