单例模式
即某个类在整个系统中只能有一个实例对象可被获取和使用的代码模式
例如:代表JVM运行环境的Runtime类
要求:
- 该类只能由一个实例
构造器私有化 - 它必须自己创建该实例
含有一个该类的静态变量来存储这个唯一实例 - 该类必须仔细向整个系统提供这个实例
存在对外提供获取这个实例对象的方式:
1)直接暴露(饿汉式)
2)用获取静态变量的get方法获取(懒汉式)
饿汉式
直接创建对象,不存在线程安全问题
public class Singleton{
//私有化构造器
private Singleton(){};
//静态变量存储,直接暴露
public static final Singleton INSTANCE = new Singleton();
}
//外部获取方式
Singleton s = Singleton.INSTANCE;
懒汉式
延迟创建对象
//适用于单线程
public class SingletonLan {
//私有化构造器
private SingletonLan(){};
//静态变量
private static SingletonLan INSTANCE;
public static SingletonLan getInstance(){
//第一次需要时创建
if(INSTANCE == null){
INSTANCE = new SingletonLan();
}
return INSTANCE;
}
}
//适用于多线程
public class SingletonLan {
private SingletonLan(){};
private static SingletonLan INSTANCE;
public static SingletonLan getInstance(){
if(INSTANCE == null){
synchronized (SingletonLan.class){
if(INSTANCE == null){
try {
//多线程下,可能存在多次线程都创建了对象,此次以线程休眠情况举例;所以加锁保证线程安全
//线程休眠
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
INSTANCE = new SingletonLan();
}
}
}
return INSTANCE;
}
}
//外部获取方式
SingletonLan s1 = SingletonLan.getInstance();