设计形式DP(2)单态模式

设计模式DP(2)单态模式 设计模式DP(2)单态模式singleton特点:一个系统内,该对象有且仅能存在一个实例该类

设计模式DP(2)单态模式

 

设计模式DP(2)单态模式singleton

特点:一个系统内,该对象有且仅能存在一个实例

           该类的实例化,交给它本身完成,外界没有创建的权力

           对外封闭性

代码:

##硬汉式和懒汉式

public class Singleton{

     private static Singleton instance = new Singleton();

     public static Singleton getInstance(){

          return instance;

    }

}

 

public class Singleton2{

     private static Singleton2 instance = null;

     public static synchronized  Singleton2 getInstance(){

              if(null == instance){ instance = new Singleton2();}         

              return instance;

    }

}