单例模式学习

单例模式顾名思义就是实现一个类只有一个实例的模式。至于如何实现,那就是八仙过海,各显神通了。

从创建实例的时间来看,单例模式分为两类:1、饿汉式,2、懒汉式

1、饿汉式

饿汉式就是比较急,在类加载的时候就完成了实例化,在使用前就已经完成实例化。

饿汉式的实现方法:使用静态变量实现,使用静态代码块实现,使用静态内部类实现,使用枚举类实现,这些实现方法是我所知道的,可能还存在其他实现方法。

1)使用静态变量实现

class SingletonDemo{ 
    //实例
    private static SingletonDemo instance = new SingletonDemo();

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

2)使用静态代码块实现

public class SingletonDemo{
    //实例
    private static SingletonDemo instance;

    static{
        instance = new SingletonDemo();
    }
    
    public static SingletonDemo getInstance(){
        return instance;
    }
}

 

3)使用静态内部类实现

public class SingletonDemo {
     
    private static class SingletonClassInstance{
        //实例
        private static final SingletonDemo instance=new SingletonDemo ();
    }
     
    private SingletonDemo (){}
     
    public static SingletonDemo getInstance(){
        return SingletonClassInstance.instance;
    }
     
}

4) 使用枚举类实现

public enum SingletonDemo {
    INSTANCE;
}

2、懒汉式

懒汉式就很懒,在使用时才进行实例的初始话。

懒汉式其实就一个思路,就是维护一个静态变量,让其在使用时判断一下该静态变量是否为空,为空则创建一个对象并赋值,否则直接返回该静态变量。只不过在多线程时涉及到线程安全问题,由此而产生很多拓展。

 1)普通懒汉式

public class SingletonPattern {

    private static SingletonPattern instance = null;

    private SingletonPattern() {
    }

    public static SingletonPattern getInstance() {
        if (instance == null) {
            instance = new SingletonPattern ();
        }
        return instance;
    }

}

 2)双重锁模式

class Singleton {
    //添加volatil修饰,防止jvm优化运行
    private volatile static Singleton singleton;
    private Singleton (){}
    public static Singleton getInstance() {
    //第一层判断,简单过滤,减少锁的创建
        if (singleton == null) {
            synchronized (Singleton.class) {
                //二层过滤,同步代码块中,保证同一时间只有一个线程在运行这块代码,保证了线程安全
                if (singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
}

 

兼听则明,偏信则暗

posted @ 2020-01-16 15:06  会飞的joy  阅读(114)  评论(0编辑  收藏  举报