单例模式

枚举能够防止单例被反射破坏,其他的不能

饿汉模式

1
2
3
4
5
6
7
public static class Hungry{
private Hungry(){}
private final static Hungry hungry = new Hungry();
public static Hungry getInstance(){
return hungry;
}
}

普通的懒汉模式

1
2
3
4
5
6
7
8
9
10
public static class Lazy{
private Lazy(){}
private static Lazy lazy;
public static Lazy getInstance(){
if (lazy==null){
lazy=new Lazy();
}
return lazy;
}
}

DCL懒汉模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static class LazyMan{
private LazyMan(){}
private static volatile LazyMan lazyMan;
public static LazyMan getInstance(){
if (lazyMan==null){
synchronized (LazyMan.class){
if (lazyMan==null){
lazyMan=new LazyMan();
}
}
}
return lazyMan;
}
}

静态内部类

1
2
3
4
5
6
7
8
9
public static class Holder{
private Holder(){}
private static class Inner{
private static final Holder holder = new Holder();
}
public static Holder getInstance(){
return Inner.holder;
}
}

枚举

1
2
3
4
5
6
7
8
//能够防止单例被反射破坏
public static enum EnumSingleton{
//测试用例
INSTANCE1, INSTANCE2,INSTANCE3;
public static EnumSingleton getInstance(){
return INSTANCE2;
}
}