什么叫单例模式
单例模式就是为确保一个类只有一个实例,并为整个系统提供一个全局访问点的一种方法。
构造方法私有化,通过公开的方法得到实例化对象
实现
饿汉模式
不管是否调用,先实例化
/**
*
*饿汉式单例
*/
public class Singleton {
private static Singleton singleton = new Singleton();
private Singleton() {};
public static Singleton getSingleton() {
return singleton;
}
}
懒汉模式
调用时再实例化
/**
*
*懒汉式单例
*/
public class Singleton{
private static Singleton singleton ;
private Singleton() {};
public static Singleton getSingleton() {
if(singleton == null) {
return new Singleton();
}
}
}
刚学单例模式的时候,总记不住它们的区别
后面我就想一个叫懒汉模式,干脆叫另一个勤快模式
勤快当然先干活儿
懒汉就是推一下动一下
线程安全的单例模式
饿汉单例模式天生就是线程安全的,因为它只创建实例化对象一次,线程每次都只能也必定只可以拿到这个唯一的对象
而懒汉模式,当多个线程同时进入if内,就会创建多个实例化对象,这样就违背了我们单例模式的初衷,所以是线程不安全的。
实现懒汉线程安全 关键字synchronized
synchronized用法:
在修饰代码块的时候需要一个reference对象作为锁的对象.
在修饰方法的时候默认是当前对象作为锁的对象.
在修饰类时候默认是当前类的Class对象作为锁的对象.
下面实现线程安全的懒汉模式
方法一 synchronized修饰方法
public class Singleton{
private static Singleton singleton ;
private Singleton() {};
public static synchronized Singleton getSingleton() {
if(singleton == null) {
return new Singleton();
}
}
}
方法二 synchronized修饰代码块 双重检查锁定
public class Singleton{
private static Singleton singleton ;
private Singleton() {};
public static Singleton getSingleton() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
方法三 静态内部类
public class Singleton{
private static class Holder {
private static Singleton singleton = new Singleton();
}
private Singleton() {};
public static Singleton getSingleton() {
return Holder.singleton;
}
}