I sometimes need classes that need to be created only once during the application life cycle. Making them one-night is bad, because then unit testing becomes problematic.
But nevertheless, since during the life cycle of my application there should be one and only instance of such objects, it would be a mistake to ever instantiate such an object twice when the application starts.
Therefore, I would like my application to throw an exception as soon as it detects during its life cycle that such an object is created twice, but at the same time allows several instances of such an object during unit testing.
I believe that this is not an unreasonable requirement: if only one such object should be created during one application life cycle, then throwing an exception seems to be correct.
That's what I'm doing:
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();
}
}
where App.isRealApp () always returns false when I test the module, and always true when the real application is running.
My question is simple: does it make sense and how should I implement it?
source
share