设计模式快速学习(三)单例模式

单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属于建立型模式,它提供了一种建立对象的最佳方式。 这种模式涉及到一个单一的类,该类负责建立本身的对象,同时确保只有单个对象被建立。这个类提供了一种访问其惟一的对象的方式,能够直接访问,不须要实例化该类的对象。编程

优势

一、在内存里只有一个实例,减小了内存的开销,尤为是频繁的建立和销毁实例(好比管理学院首页页面缓存)。设计模式

二、避免对资源的多重占用(好比写文件操做)。缓存

缺点

没有接口,不能继承,与单一职责原则冲突,一个类应该只关心内部逻辑,而不关心外面怎么样来实例化。安全

实现方式一:懒汉式(线程不安全)

懒汉式:就是用的时候再进行实例化对象。bash

public class Singleton {  
    private static Singleton instance;  
    private Singleton (){}  
  
    public static Singleton getInstance() {  
    if (instance == null) {  
        instance = new Singleton();  
    }  
    return instance;  
    }  
}
复制代码

这种实现方式不支持多线程,由于没有同步锁,多线程下不能正常工做。多线程

实现方式二:懒汉式(线程安全)

public class Singleton {
    private static Singleton instance;

    public static synchronized Singleton getInstance(){
        if (instance == null){
            instance = new Singleton();
        }
        return instance;
    }
}
复制代码

能够在多线程环境下使用,可是效率过低。并发

优势:一个对象初始化一次,节省内存。性能

缺点:必须用synchronized来维持单例,没效率。测试

实现方式三:饿汉式(线程安全)

public class Singleton {
    private static Singleton instance = new Singleton();

    public static Singleton getInstance(){
        return instance;
    }
}
复制代码

由于它做为静态资源,因此在类装载时就被实例化ui

优势:没有加锁,执行效率会提升。

缺点:类加载时就初始化,浪费内存。

实现方式四:双检锁/双重校验锁DCL(线程安全)

public class Singleton {
    private static Singleton instance;

    public static Singleton getInstance(){
        if (instance == null){
            synchronized (Singleton.class){
                if (instance == null){
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}
复制代码

采用双锁机制,安全且在多线程状况下能保持高性能。详细了解请点击:Java并发编程 -- 单例模式线程安全问题

实现方式五:登记式/静态内部类(线程安全)

public class Singleton {
    private static Singleton instance;

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

    public static Singleton getInstance(){
        return SingletonHandler.INSTANCE;
    }
}
复制代码

这种方式能够说是恶汉式的变通版,SingletonHandler没有被主动使用的状况下是不会实例化Singleton对象的,因此这样作,既能达到lazy式的加载,又能保证线程安全。

实现方式六:枚举类(线程安全)

public enum  Singleton {
    INSTANCE;
    public void myMethod() {
        System.out.println("enum instance test");
    }
}
复制代码

它不只能避免多线程同步问题,并且还自动支持序列化机制,防止反序列化从新建立新的对象,绝对防止屡次实例化。

测试:

public class Main {
    public static void main(String[] args) {
        Singleton singleton = Singleton.INSTANCE;
        singleton.myMethod();
    }
}
复制代码
enum instance test
复制代码

总结

不建议使用第 1 种和第 2 种懒汉方式,建议使用第 3 种饿汉方式。只有在要明确实现 lazy loading 效果时,才会使用第 5 种登记方式。若是涉及到反序列化建立对象时,能够尝试使用第 6 种枚举方式。

相关文章
相关标签/搜索