类和对象——单例设计模式

单例设计模式:

解决一个类在内存只存在的一个对象

 

//getInstance()    返回对象

饿汉式:先初始化对象

class Si{

private static Si s=new SI();

private Si(){ }

public static Si getInstance(){

return s;

  }

}

懒汉式:

class Si{

private static Si s=null;

private Si(){ }

public static Si getInstance(){

        if(s==null)

            s=new Si();

      return s;

    }

}

 

posted @ 2018-10-15 16:08  StingLon  阅读(128)  评论(0)    收藏  举报