单身java,java – 如何实现近单身?

我有时需要只在应用程序生命周期中实例化一次的类.让他们成为单身人士是不好的,因为单元测试变得有问题.

但是,因为在我的应用程序的生命周期中应该有这样的对象的唯一实例,所以在应用程序运行时将这样的对象实例化两次是错误的.

因此,我希望我的应用程序在其生命周期中检测到这样的对象被实例化两次,同时仍然允许在单元测试时对这样的对象进行多次实例化时抛出异常.

我认为这不是一个不合理的要求:如果在应用程序的一个生命周期中只应创建一个这样的对象,那么抛出异常似乎是正确的事情.

这是我正在做的事情:

/**

* The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT",

* "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this

* document are to be interpreted as described in RFC 2119.

*

* You MUST NOT instantiate this class more than once during the application's

* lifecycle. If you try to do so, an exception SHALL be thrown.

*

* You SHOULD be able to instantiate this class more than once when unit

* testing.

*

*

*/

public class LifeCycle {

private static final AtomicInteger cnt = new AtomicInteger( 0 );

@NotNull

public static LifeCycle getNewLifeCycle() {

if ( cnt.incrementAndGet() > 1 && App.isRealApp() ) {

throw new IllegalStateException("Class is already instantiated");

}

return new LifeCycle();

}

}

其中App.isRealApp()在我进行单元测试时总是返回false,并且在真实应用程序运行时始终为true.

我的问题很简单:它是否有意义,我应该如何实现这一点?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值