我有时需要在应用程序的生命周期中只应该实例化一次的类。让他们单身是不好的,因为然后单元测试就成了问题。如何实现一个近单身?
但是,由于在我的应用程序的生命周期中应该只有一个这样的对象的实例,因此在应用程序运行时将这样的对象两次实例化为将是错误。
因此,我想我的应用程序尽快检测抛出一个异常,它的生命周期中,这样的一个对象实例化两次同时仍然允许这种对象的几个实例,而单元测试。
我认为这不是一个不合理的要求:如果在应用程序的一个生命周期中只有一个这样的对象应该被创建,那么抛出异常似乎是一个正确的事情。
下面是我在做什么:
/**
* 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()应始终返回假当我的单元测试,并始终真正当真正的应用程序正在运行。
我的问题很简单:它有道理,我该如何实现?
+1,我喜欢轻量级的代理理念! – NoozNooz42 2010-12-23 18:36:14
这对我很有用 - 意味着我可以保持代码基本不变。 – 2010-12-23 18:58:19