单例模式
饿汉式
在类初始化时直接创建实例对象,不管你是否需要这个对象都会创建
普通写法
- 构造器私有化
- 自行创建,并且用静态变量保存
- 向外提供这个实例
- 强调这是一个单例,我们可以用final修饰
public class Singleton1{
public static final Singleton1 INSTANCE = new Singleton1();
private Singleton1(){
}
}
枚举enum
- 枚举类,标识该类型的对象是有限的几个
- 我们可以限定为一个,就成了单例
public enum Singleton2{
INSTANCE
}
静态代码块
public class Singleton {
private Singleton(String info) {
this.info = info;
}
private String info;
public static Singleton INSTANCE = null;
static {
try {
Properties pro = new Properties();
pro.load(Singleton.class.getClassLoader().getResourceAsStream("xq.properties"));
INSTANCE = new Singleton(pro.getProperty("info"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
懒汉式
延迟创建这个实例对象
普通写法(线程不安全)
- 构造器私有化
- 用一个静态变量保存这个唯一的实例
- 提供一个静态方法,获取这个实例对象
public class Singleton1 {
private static Singleton1 instance;
private Singleton1() {
}
public static Singleton1 getInstance(){
if (instance == null){
instance = new Singleton1();
}
return instance;
}
}
考虑线程安全性和效率
public class Singleton1 {
private static Singleton1 instance;
private Singleton1() {
}
public static Singleton1 getInstance() {
//性能
if (instance == null) {
synchronized (Singleton1.class) {
try {
if (instance == null) {
Thread.sleep(100);
instance = new Singleton1();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
return instance;
}
}
内部类
在内部类被加载和初始化时,才创建INSTANCE实例对象
静态内部类不会自动随着外部类的加载和初始化而初始化,它是要单独去加载和初始化的
因为是在内部类初始化时加载和初始化,因此是线程安全的
public class Singleton2 {
private Singleton2(){
}
private static class Inner{
private static final Singleton2 instance = new Singleton2();
}
public static Singleton2 getInstance(){
return Inner.instance;
}
}
4167

被折叠的 条评论
为什么被折叠?



