How to realize the near singleton?

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:

/**
 * 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();
    }

}

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?

+5
source share
3 answers

If your design requires a singleton, then your best bet is to use a singleton rather than try something complicated.

, , , , , , .

- - .

​​ . - .

+9

-, Spring.

singleton, - .

: http://static.springsource.org/spring/docs/2.5.x/reference/testing.html

, , , Singleton.getInstance() true factory, . , , , , , factory ( , JDK DocumentBuilderFactory).

+5

, , , ,

, Singleton.

.

You can do this with @ com.dp4j.Singleton

That allows API Reflection.

You can use the Reflection API directly or add dp4j for it. Here you will find the code for both.

0
source

All Articles