设计模式

2017-07-14  本文已影响0人  被虐的小鸡

设计模式(一)


单例设计模式

单例就是某个实体只产生一个对象,如果只能产生一个对象那么就需要将构造函数设置为private的,那么就无法手动去创建该类的实体对象。

public class Student {

     private Student(){}

     private static Student s=new Student();

     public static Student getInstance(){

          return s;

     }

}

由于在类中直接创建除了实体的对象,这种方式被称为饿汉式。但是如果创建该对象的时候需要消耗大量的资源,那么在不使用该对象的时候尽量不要去初始化

public class Student {

     private Student(){

     //消耗很多资源

     }

     private static Student s;

     public static Student getInstance(){

          if(s==null){

               s=new Student();

          }

          return s;

     }

}

上面这种方式避免了在不需要使用实体对象的时候对实体对象进行初始化,但是在多线程并发的时候,会出现线程1执行到s=new Student()的时候线程2执行到if(s==null),这个时候就有可能创建两个实体对象,为了避免以上的情况出现需要添加synchronized关键字。

public class Student {

     private static Student s;

     private Student(){}

     public static Student getInstance(){

          if(s == null){

               synchronized(Student.class){

                    if(s == null){

                         s = new Student();

                    }

               }

          }

          return instance;

     }

}

上一篇 下一篇

猜你喜欢

热点阅读