仅为类创建一个对象并重用相同的对象 [英] Create only one object for a class and reuse same object

查看:168
本文介绍了仅为类创建一个对象并重用相同的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to create only one object of an class and reuse the same object over and over again. Is there any efficient way to do this.

我该怎么做?

推荐答案

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

这篇关于仅为类创建一个对象并重用相同的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆