【问题标题】:Creating a singleton class创建单例类
【发布时间】:2016-02-21 13:30:11
【问题描述】:

Singleton 的目的是控制对象的创建,将对象的数量限制为一个。下面是一个有两个公共方法的类。我想将其转换为单例类。是否放置一个私有构造函数足以将类转换为单例类?我们可以通过哪些其他方式将类设为单例?

 public class Singleton {


    public void abc(){
    }

    public void def()
    {
    }
 }

【问题讨论】:

  • 谷歌亲爱的先生。发布前谷歌

标签: android object singleton


【解决方案1】:

确实,发帖前先谷歌一下。 这是一个 Singleton 类的实现。

public class MySingleton {
    private static MySingleton mInstance= null;

    private MySingleton (){}

    public static synchronized MySingleton getInstance(){
        if(null == mInstance){
            mInstance = new MySingleton();
        }
        return mInstance;
    }
}

并像这样使用它:

MySingleton.getInstance().whateverMethodYouWant();

【讨论】:

    猜你喜欢
    • 2011-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-28
    • 2020-04-24
    相关资源
    最近更新 更多