设计模式-单例

Posted alex_cool

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式-单例相关的知识,希望对你有一定的参考价值。

单例模式是一种常见的设计模式

单例模式有以下特点:

  1、单例类只能有一个实例。
  2、单例类必须自己创建自己的唯一实例。
  3、单例类必须给所有其他对象提供这一实例。

 

饿汉式单例

public class Singleton {

    private static Singleton instance = new Singleton();

    public static Singleton getInstance() {
        return instance;
    }
}

在类创建的同时就已经创建好一个静态的对象供系统使用,以后不再改变

 

懒汉式单例

public class Singleton {

    private static Singleton instance = null;

    /**
     * 懒汉模式一 
     * 同步方法
     */
    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }

        return instance;
    }

    /**
     * 懒汉模式二 
     * 同步代码块
     */
    public static Singleton getInstance() {
        synchronized (Singleton.class) {
            if (instance == null) {
                instance = new Singleton();
            }
        }

        return instance;
    }
}

同步代码,或者同步代码块,效率低

 

双重锁检查

public class Singleton {

    private static volatile Singleton instance = null;

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }

        return instance;
    }
}

线程安全,提高效率

 

内部静态类

public class Singleton {

    private static class SingletonHandler {
        private static Singleton instance = new Singleton();
    }

    public static Singleton getInstance() {
        return SingletonHandler.instance;
    }
}

 

以上是关于设计模式-单例的主要内容,如果未能解决你的问题,请参考以下文章

常用代码片段

性能比较好的单例写法

片段作为 Android 中的单例

单例片段或保存网页视图状态

从 Viewpager2 片段访问父片段函数

你熟悉的设计模式都有哪些?写出单例模式的实现代码