最精简:设计模式之单例模式
懒汉式(线程不安全)
public class SingletonLazy {
public static void main(String[] args) {
Order instance = Order.getInstance();
Order instance2 = Order.getInstance();
System.out.println(instance == instance2);
}
}
class Order{
private Order(){
}
private static Order instance = null;
public static Order getInstance(){
if (instance == null) {
return instance = new Order();
}else {
return instance;
}
}
}
懒汉式(线程安全)双重检测:DCL懒汉式()
public class SingletonLazy {
public static void main(String[] args) {
Order instance = Order.getInstance();
Order instance2 = Order.getInstance();
System.out.println(instance == instance2);
}
}
class Order {
private Order() {
}
private static Order instance = null;
public static Order getInstance() {
if (instance == null) {
synchronized (Order.class) {
if (instance == null) {
return instance = new Order();
}
}
}
return instance;
}
}
懒汉式(线程安全)
DCL懒汉式在return instance = new Order();的时候如果有多线程存在的情况下会发生指令重排的情况,所有并不是绝对安全的,解决方法是在private static Order instance = null;上加上Volatile关键字
public class SingletonLazy {
public static void main(String[] args) {
Order instance = Order.getInstance();
Order instance2 = Order.getInstance();
System.out.println(instance == instance2);
}
}
class Order {
private Order() {
}
private volatile static Order instance = null;
public static Order getInstance() {
if (instance == null) {
synchronized (Order.class) {
if (instance == null) {
return instance = new Order();
}
}
}
return instance;
}
}
饿汉式
public class SingletonHunger {
public static void main(String[] args) {
Bank bank = Bank.getInstance();
Bank bank2 = Bank.getInstance();
System.out.println(bank == bank2);
}
}
class Bank{
private Bank(){
}
private static Bank instance = new Bank();
public static Bank getInstance(){
return instance;
}
}