設計模式-<單例模式> – JAVA編程語言程序開發技術文章

package 單例模式;

public class SingletonPattern {
  private volatile static SingletonPattern singletonPattern=null;
  private SingletonPattern(){
    
  }
  public static SingletonPattern getSingletonPattern() {
    /**
     * <1> In Thread synchronized
     */
    if(singletonPattern==null){
      synchronized (SingletonPattern.class) {
        if(singletonPattern==null){
        singletonPattern=new SingletonPattern();
        }
      }
    }
    /**
     * <2>
     */
    singletonPattern=SingletonPatternInstance.instance;
    
    return singletonPattern;
  }
  private static class SingletonPatternInstance{
    private static SingletonPattern instance=new SingletonPattern();
  }
   
  public void say()
  {
    System.out.println("hello world");
  }
  /**
    * @param   
    */
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    SingletonPattern.getSingletonPattern().say();
  }

}

 

本文出自 “飛沙” 博客

發佈留言