2019年5月13日 星期一

7天學會設計模式 CHAP02 單例模式 Singleto

7天學會設計模式
http://www.books.com.tw/products/0010750585

chap02.
單例模式 Singleton
目的:保證一個類別只會產生一個物件,而且要提供存取物件的統一方法。
package com.ssc24.chap02.demo01;
public class Singleton {
private static Singleton instance = new Singleton();
 private Singleton() { 
 }
 public  static Singleton getInstance() {
  if (instance == null) {
   synchronized(Singleton.class) {
    instance = new Singleton();
   }
  }
  return instance;
 }
}

package com.ssc24.chap02.demo01;
public class SingletonGreed {
 private static SingletonGreed instance = new SingletonGreed();
 
 private SingletonGreed() {
 }
 public static SingletonGreed getInstance() {
  return instance;
 }
}

package com.ssc24.chap02.demo01;
public class SingletonTest extends Thread {
 String myId;
 public SingletonTest(String id){
  myId = id;
 }
 public void run() {
  Singleton singleton = Singleton.getInstance();
  if (singleton != null) {
   System.out.println(myId + "產生Singleton:" + singleton.hashCode());
  }
 }
 public static void main(String[] args) {
  /**
  Singleton s1 = Singleton.getInstance();
  Singleton s2 = Singleton.getInstance();
  System.out.println("S1:" + s1.hashCode() + "\nS2:" + s2.hashCode());
  */
  Thread t1 = new SingletonTest("執行緒T1");
  Thread t2 = new SingletonTest("執行緒T2");
  t1.start();
  t2.start();
 }
}

/**
執行緒T1產生Singleton:935563448
執行緒T2產生Singleton:935563448
**/