java单例的四个小案例
1
package com.example.youruan.day01.entity;
public class Singleton1 {
private Singleton1() {
}
private static final Singleton1 singletonInstance = new Singleton1();
public static Singleton1 getInstance() {
return singletonInstance;
}
}
2
package com.example.youruan.day01.entity;
public class Singleton2 {
private static Singleton2 instance = null;
public static synchronized Singleton2 getInstance() {
if (instance == null)
instance = new Singleton2();
return instance;
}
}
3
package com.example.youruan.day01.entity;
public class Singleton3 {
private static volatile Singleton3 instance = null;
public static Singleton3 getInstance() {
if (instance == null) {
synchronized (Singleton3.class) {
if (instance == null) {
instance = new Singleton3();
}
}
}
return instance;
}
}
4
package com.example.youruan.day01.entity;
public class Singleton4 {
private static class Holder {
static final Singleton4 instance = new Singleton4();
}
public static Singleton4 getInstance() {
return Holder.instance;
}
}