单例设计模式
什么是Singleton?
单例设计模式,即某个类在整个系统中只能有一个实例对象可被获取和使用的代码模式。
要点
- 某个类只能有一个实例
- 构造器私有化
- 必须自行创建这个实例
- 含有一个该类的静态变量来保存这个唯一的实例
- 必须自行向整个系统提供这个实例
- 对外提供获取该实例对象的方式:
(1)直接暴露 (2)用静态变量的get方法获取
- 对外提供获取该实例对象的方式:
几种常见形式
- 饿汉式:直接创建对象,不存在线程安全问题
- 直接实例化饿汉式(简洁直观)
- 枚举式(最简洁)
- 静态代码块饿汉式(适合复杂实例化)
- 懒汉式:延迟创建对象
- 线程不安全(适合单线程)
- 线程安全(适合多线程)
- 静态内部类形式(适合多线程)
相应代码
直接实例化饿汉式
public class Singleton1 {
public static final Singleton1 INSTANCE = new Singleton1();
private Singleton1(){
}
}
枚举类型
public enum Singleton2 {
INSTANCE
}
静态代码块
public class Singleton3 {
public static final Singleton3 INSTANCE;
private String info;
static {
Properties pro = new Properties();
try {
pro.load(Singleton3.class.getClassLoader().getResourceAsStream("single.properties"));
INSTANCE = new Singleton3("info");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private Singleton3(String info){
this.info = info;
}
}
线程不安全
public class Singleton4 {
private static Singleton4 instance;
private Singleton4(){
}
public static Singleton4 getInstance() throws InterruptedException {
if (instance==null){
Thread.sleep(1000);
instance = new Singleton4();
}
return instance;
}
}
线程安全
private static Singleton5 instance;
private Singleton5(){
}
public static Singleton5 getInstance() throws InterruptedException {
if(instance==null) {
synchronized (Singleton5.class) {
if (instance == null) {
Thread.sleep(1000);
instance = new Singleton5();
}
}
}
return instance;
}
静态内部类
public class Singleton6 {
private static Singleton6 instance;
private Singleton6(){
}
private static class Inner{
private static final Singleton6 INSTANCE = new Singleton6();
}
public static Singleton6 getInstance(){
return Inner.INSTANCE;
}
}