常见的单例模式
作者:互联网
1.懒汉式
public class HungryMan {
private HungryMan(){}
private static HungryMan hungryMan = new HungryMan();
public static HungryMan getInstance(){
return hungryMan;
}
}
优点:简单方便
缺点:无论是否会用到,都会实例化,而且在类加载时就实例化,降低程序启动速度。
2.饿汉式
public class LazyMan {
private static LazyMan lazyMan = null;
private LazyMan() {
}
public static LazyMan getInstatce() {
if (lazyMan == null) {
lazyMan = new LazyMan();
}
return lazyMan;
}
}
优点:在使用时才会生成对象,能够减少内存开销。
缺点:线程不安全,只适用单线程,当有多个线程访问时,能够产生多个对象,不满足单例模式的要求。
3.懒汉式同步锁
public class LazyMan {
private static volatile LazyMan lazyMan = null;
private LazyMan() {
}
public static LazyMan getInstatce() {
synchronized (LazyMan.class){
if (lazyMan == null) {
lazyMan = new LazyMan();
}
}
return lazyMan;
}
}
优点:支持多线程;
缺点:每次都会加锁和释放锁操作,效率低,可通过反射破坏单例模式。
4.饿汉式双重校验锁(既加锁又判空)
public class LazyMan {
private static volatile LazyMan lazyMan = null;
private LazyMan() {
}
public static LazyMan getInstatce() {
if(lazyMan == null){
synchronized (LazyMan.class){
if (lazyMan == null) {
lazyMan = new LazyMan();
}
}
}
return lazyMan;
}
}
优点:效率高,线程安全。
缺点:代码复杂,可通过反射破坏单例模式。
5.静态内部类
public class SingleStatic {
private SingleStatic() {
}
private static class SingleB {
public static SingleStatic singleStatic = new SingleStatic();
}
public static SingleStatic getInstance() {
return SingleB.singleStatic;
}
}
优点:使用时才会加载,而且静态内部变量只加载一次所以线程安全;
缺点:代码变得复杂,apk文件增大。
6.枚举类
public enum SingleTon {
SINGLE_TON;
private String field;
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
}
优点:线程安全,不用担心反射破坏单例模式。
缺点:枚举类占用内存多。
标签:class,常见,模式,public,LazyMan,static,private,单例,lazyMan 来源: https://www.cnblogs.com/PrinceZaZa/p/16243390.html