设计模式
单例设计模式
饿汉模式
- 饿汉模式的规则,就是在类导入的时候就创建好一个单例,不管该单例是否有用
- 创建条件
- 创建的单例在类中
- private 私有
- static 静态(这样在类的导入时才会创建)
- final 常量(保证创建的类不会更改)
- 私有化的构造器
- getInstance()
public class God{
private static final god = new God();
private God(){};
private static God getInstance(){
return god;
}
}
懒汉模式
- 饿汉模式在创建实例的时候要是长时间没有人使用这个单例,则会造成内存的浪费。所以懒汉模式应运而生
- 创建条件:
- 去掉 final 关键字,因为在创建的时候添加final则在后续无法初始化
- synchronized 保证线程同步
public class God{
private static God god;
private God(){};
private static synchronized God getInstance(){
if(god == null){
god = new God();
}
return god;
}
}
优化线程处理
- 因为多个用户在访问 getInstance 的时候就会阻塞,导致还没进到方法中就排队
- 所以将 synchronized 写在实例为空的时候,这样实例不为空的时候就不会阻塞
public class God{
private static God god;
private God();
private static God getInstance(){
if(god == null){
synchronized(Sun.class){
if(god == null){
god = new God();
}
}
}
}
}