饿汉式
代码语言:javascript复制class Bank{
private Bank(){}
private static Bank instance = new Bank();
public static Bank getInstance(){
return instance;
}
}
懒汉式
代码语言:javascript复制class Order{
private Order(){}
private static Order instance = null;
public static Order getInstance(){
if(instance == null){
synchronized(Order.class){
if(instance == null){
instance = new Order();
}
}
}
return instance;
}
}
synchronized
解决线程安全问题
饿汉式与懒汉式
- 饿汉式:
- 对象加载时间过长
- 懒汉式:
- 延迟对象创建