设计一个类,让它只能实例化3次,怎么实现啊?

解决方案 »

  1.   

    定义一个static变量来控制,通过工厂来或得实例。这样的话当到达三次的是很将会不能再获得实例。不知道这是不是你要的需求
      

  2.   

    或者只产生3个instance可以吗?用单例 先private structure(){}然后getInstanceNo1(){}
    getInstanceNo2(){}
    getInstanceNo3(){}
      

  3.   

    这和单例没有什么太大的区别。用类似单例的静态方法里面去判断可以。或者 构造函数判断超过次数的时候抛异常也可以。二楼的意见应该没有问题。
    方案1:public class TripleInstance {
    private static int count = 0; private static final int shieldValue = 3; private TripleInstance() { } public static TripleInstance getInstance() {
    TripleInstance obj = null;
    if (count < shieldValue) {
    count++;
    obj = new TripleInstance();
    }
    return obj;
    }
    }
    方案2:public class TripleInstance {
    private static int count = 0; private static final int shieldValue = 3; public TripleInstance() throws Exception {
    if (count >= shieldValue) {
    throw new Exception("More than three times");
    } count++;
    }}
      

  4.   

    应该用static数据成员控制吧,或者用RTTI