仅为类创建一个对象并重用相同的对象

Aja*_*tha 7 java

我想只创建一个类的一个对象,并一遍又一遍地重用同一个对象.有没有有效的方法来做到这一点.

我怎样才能做到这一点?

Dis*_*tum 10

public final class MySingleton {
    private static volatile MySingleton instance;

    private MySingleton() {
        // TODO: Initialize
        // ...
    }

    /**
      * Get the only instance of this class.
      *
      * @return the single instance.
      */
    public static MySingleton getInstance() {
        if (instance == null) {
            synchronized (MySingleton.class) {
                if (instance == null) {
                    instance = new MySingleton();
                }
            }
        }
        return instance;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @AjayGopalShrestha在去单身人士之前三思而后行.[在大多数情况下它们都是邪恶的](http://stackoverflow.com/questions/1300655/whats-alternative-to-singleton). (3认同)