在看 Design Pattern 時,有一種模式叫做工廠模式也就是 Factory Pattern,它主要的好處是在 new 一個物件時可以統一的去管理物件,當我們的程式有很多地方有 new 同一個物件很多次時,這時侯使用工廠模時就會變得很好用。如果程式要去修改也會變的比較方便,只要去修改產生 instance 的地方就行了。
內建的 Java 也有提供 ThreadFactory 的 Interface 供我們去實作建立 Thread 的工廠模式,以下的 Sample 是沒有使用 ThreadFactory 的部份:
public class ThreadExample implements Runnable {
  private String message;
  public ThreadExample(String message) {
    this.message = message;
  }
  @Override
  public void run() {
    System.out.println(this.message);
  }
}
public class Test {
  public static void main(String args[]) {
    ThreadExample a = new ThreadExample("message1");
    Thread thread1 = new Thread(a);
    ThreadExample b = new ThreadExample("message2");
    Thread thread2 = new Thread(b);
    ThreadExample c = new ThreadExample("message3");
    Thread thread3 = new Thread(c);
    thread1.start();
    thread2.start();
    thread3.start();
  }
}
以上的程式就是開啟 Thread 最基本的寫法,使用這種寫法有一個缺點就是無法知道目前 new 了多少的 Thread 的 instance,如果使用 Factory 的做法它就可以在 new 完一個 Thread 之後放入一個 count 的計數器統計目前 new 了多少的 Thread,另外一個缺點就是如果要修改 new Thread 程式的寫法需要修改三次,但是如果使用 Factory 的做法只要給一次就可以了,以下就簡單寫一個 ThreadFactory 的 Sample Code,程式如下:
import java.util.concurrent.ThreadFactory;
public class ThreadFactoryExample implements ThreadFactory {
  private int count = 0;
  @Override
  public Thread newThread(Runnable r) {
    count = count + 1;
    return new Thread(r);
  }
  public int getCount() {
    return count;
  }
}
以上的程式主要會去實作 java.util.concurrnet 的 ThreadFactory,然後會在 newThread 的方法裡去統計目前建立了幾個 Thread 的 instance,如果之後需要修改建立 instance 的程式邏輯也可以在 newThread 的方法去修改。
public class Test {
  public static void main(String args[]) {
    ThreadFactoryExample factory = new ThreadFactoryExample();
    Thread thread1 = factory.newThread(new ThreadExample("message1"));
    Thread thread2 = factory.newThread(new ThreadExample("message2"));
    Thread thread3 = factory.newThread(new ThreadExample("message3"));
    System.out.println(factory.getCount());
    thread1.start();
    thread2.start();
    thread3.start();
  }
}
在主程式的方面就會先建立 factory,之後 Thread 的 instance 都可以用此 factory 去產生,之後就可以呼叫 getCount 去得到目前建立多少的 instance。 ThreadExample 的程式如下:
public class ThreadExample implements Runnable {
  private String message;
  public ThreadExample(String message) {
    this.message = message;
  }
  @Override
  public void run() {
    System.out.println(this.message);
  }
}
以上執行緒程式簡單的印出 mesage 變數的字串,執行結果如下:
3
message1
message2
message3
使用 factory pattern 可以幫助我們在維護程式較方便。