设计一个类,让它只能实例化3次,怎么实现啊? 设计一个类,让它只能实例化3次,怎么实现啊? 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 定义一个static变量来控制,通过工厂来或得实例。这样的话当到达三次的是很将会不能再获得实例。不知道这是不是你要的需求 或者只产生3个instance可以吗?用单例 先private structure(){}然后getInstanceNo1(){}getInstanceNo2(){}getInstanceNo3(){} 这和单例没有什么太大的区别。用类似单例的静态方法里面去判断可以。或者 构造函数判断超过次数的时候抛异常也可以。二楼的意见应该没有问题。方案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++; }} 应该用static数据成员控制吧,或者用RTTI java 中CardLayout布局模式问题 关于异常处理 jtree的问题 jsp+servlet 如何实现自动备份数据库? 求一个工具类,能把'一',‘二’,‘二十一’等中文数字转换为阿拉伯数字1,2,21等 java中如何格式化一个字符串 感谢关心和帮助过我的朋友,祝福Java版所有兄弟姐妹新年快乐! 我在JB7的IDE编辑程序,为何光标与当前编辑位置常对不上,别扭呀,怎样设定才避免? 送分啦!一个关于变量定义的简单问题! 新手:JAVA在LINUX下的运行,有经验者请进! 一道线程问题 2个很弱的问题
getInstanceNo2(){}
getInstanceNo3(){}
方案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++;
}}