单例模式
懒汉模式
public class Lazy{
private volatile static Lazy lazy;
private Lazy(){
}
public static Lazy getLazy() throws InterruptedException {
if (lazy==null){
synchronized (Lazy.class) {
if (lazy == null) {
lazy = new Lazy();
}
}
}
return lazy;
}
}
测试类
public class LazySingleton {
public static void main(String[] args) {
new Thread(()->{
try {
Lazy lazy = Lazy.getLazy();
System.out.println(lazy);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(()->{
try {
Lazy lazy2 = Lazy.getLazy();
System.out.println(lazy2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}
饿汉模式
public class Hungry{
private static Hungry hungry = new Hungry();
private Hungry(){
}
public static Hungry getHungry(){
return hungry;
}
}
测试类
public class HungrySingeton {
public static void main(String[] args) {
new Thread(()->{
System.out.println(Hungry.getHungry());
}).start();
new Thread(()->{
System.out.println(Hungry.getHungry());
}).start();
}
}
静态内部类
public class Inside{
private static class InsideHolder{
private static Inside inside = new Inside();
}
private Inside(){
}
public static Inside getInside(){
return InsideHolder.inside;
}
}
测试类
public class InsideSingleton {
public static void main(String[] args) {
new Thread(()->{
System.out.println(Inside.getInside());
}).start();
new Thread(()->{
System.out.println(Inside.getInside());
}).start();
}
}
利用反射破坏单例
以静态内部类为例
public class Inside{
private static class InsideHolder{
private static Inside inside = new Inside();
}
private Inside(){
}
public static Inside getInside(){
return InsideHolder.inside;
}
}
测试类
public class InsideSingleton {
public static void main(String[] args) throws Exception{
Constructor<Inside> constructor = Inside.class.getDeclaredConstructor();
constructor.setAccessible(true);
Inside inside = constructor.newInstance();
Inside inside1 = Inside.getInside();
System.out.println(inside==inside1);
}
}
枚举实现单例
public enum Enum{
ENUM;
public void print(){
System.out.println(this.hashCode());
}
}
测试类
public class EnumSingleton {
public static void main(String[] args) {
Enum e1 = Enum.ENUM;
Enum e2 = Enum.ENUM;
System.out.println(e1==e2);
}
}