java – 只为类创建一个对象并重用相同的对象

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

我怎样才能做到这一点?

解决方法

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;
    }
}

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...