31 设计模式01-单例模式

2020-08-11  本文已影响0人  张力的程序园

单例模式,顾名思义,就是无论采用何种方式去创建,都要确保只能创建出一个对象出来。

public class Student {
    private static Student instance = new Student();
    private Student(){}
    public static Student getInstance()
    {
        return instance;
    }
}
public class Student {
    private static Student instance = null;
    private Student(){}
    public static synchronized Student getInstance() {
        if(instance == null){
            instance = new Student();
        }
        return instance;
    }
}

给getInstance方法加synchronized的原因在于保证任何一个瞬间只能有一个线程进来创建对象,但这样的加锁方式太重。

public class Student {
    private static Student instance = null;
    private Student(){}
    public static Student getInstance() {
        if(instance==null)//避免每次进来都先加锁
        {
            synchronized (instance)
            {
                if(instance == null)//确保没有对象才去执行创建对象语句
                {
                    instance = new Student();
                }
            }
        }
        return instance;
    }
}
public class Student {
    private volatile static Student instance = null;
    private Student(){}
    public static Student getInstance() {
        if(instance==null)//避免每次进来都先加锁
        {
            synchronized (instance)
            {
                if(instance == null)//确保没有对象才去执行创建对象语句
                {
                    instance = new Student();
                }
            }
        }
        return instance;
    }
}
public class Student{
    private Student(){}

    private static class SingleTonHolder{
        private static Student instance = new Student();
    }

    public static Student getInstance(){
        return SingleTonHolder.instance;
    }
}

外部类加载时并不需要立即加载内部类,内部类不被加载则不去初始化instance,故而不占内存,而当Student第一次被加载时,并不需要去加载SingleTonHolder,只有当getInstance()方法第一次被调用时,才会去初始化instance,第一次调用getInstance()方法会导致虚拟机加载SingleTonHolder类,这种方法不仅能确保线程安全,也能保证单例的唯一性,同时也延迟了单例的实例化,但静态内部类单例没发传递参数。

public class TestEnum{
    public static void main(String[] args) {
        Student student1 = StudentEnum.SINGLETON.getInstance();
        Student student2 = StudentEnum.SINGLETON.getInstance();
        System.out.println(student1 == student2);
    }
}

enum  StudentEnum {
    SINGLETON;
    private Student student = null;
    private StudentEnum(){
        student = new Student();
    }
    public Student getInstance(){
        return student;
    }
}
class Student{
}

以上就是实现单例的多种方式。

上一篇 下一篇

猜你喜欢

热点阅读