单例模式

来源:互联网 发布:mac office2016破解版 编辑:程序博客网 时间:2024/05/16 07:18

单例模式分为懒汉式单例模式与饿汉式单例模式

懒汉式单例模式:(第一次调用方法的时候对象创建)

1.代码如下:

public class testSingletonPojo {      private testSingletonPojo() {}      private static testSingletonPojo t = null;       //静态工厂方法       public static testSingletonPojo getInstance(){         if (t == null){          t = new testSingletonPojo();     }    return t;}

以上的代码线程不安全.
解决懒汉式单例模式的方法:
a: 在getInstance上加同步方法:

  public static synchronized testSingletonPojo getInstance(){    if (t == null){        t = new testSingletonPojo();    }    return t;}

b: 内部静态类(提倡使用)

    public class testSingletonPojo {        private static class LazyHolder {           private static final testSingletonPojo INSTANCE = new testSingletonPojo();        }        private testSingletonPojo (){}        public static final testSingletonPojo getInstance() {           return LazyHolder.INSTANCE;        }    }   

饿汉式单例模式:(类加载的时候对象创建,线程是安全的)

 public class testSingletonPojo2{     private testSingletonPojo2(){}     private static testSingletonPojo2 t = new testSingletonPojo2();     private static testSingletonPojo2 getInstance(){     return t;     }}
原创粉丝点击