1. 程式人生 > 實用技巧 >Chapter 2. Creating and Destroying Objects 第二章節 建立和銷燬物件

Chapter 2. Creating and Destroying Objects 第二章節 建立和銷燬物件

  THIS chapter concerns creating and destroying objects: when and how to create them, when and how to avoid creating them, how to ensure they are destroyed in a timely manner, and how to manage any cleanup actions that must precede their destruction.

點選展開中文翻譯 章節關注建立和銷燬獨享:何時以及如何去建立他們,何時以及如何去避免建立他們,如何確保他們及時得被銷燬,以及如果管理在銷燬他們之前必須進行的清理行動。

Item 1: Consider static factory methods instead of constructors 考慮靜態工程函式取代建構函式

  The traditional way for a class to allow a client to obtain an instance is to provide a public constructor. There is another technique that should be a part of every programmer’s toolkit. A class can provide a public static factory method, which is simply a static method that returns an instance of the class. Here’s a simple example from Boolean

(the boxed primitive class for boolean). This method translates a boolean primitive value into a Boolean object reference:

點選展開中文翻譯 允許客戶端獲取例項的傳統方法是提供一個公共建構函式。還有另一種技巧就是成為每個程式工具包的一部分。一個類可以提供一個公共靜態工廠方法,它只是一個返回類例項的靜態方法。下面是一個簡單例子就是`Boolean`(`boolean`的簡單的裝箱類)。這個函式將`boolean`原始值轉化為`Boolean`物件引用:
public static Boolean valueOf(boolean b) {
    return b ? Boolean.TRUE : Boolean.FALSE;
}

  Note that a static factory method is not the same as the Factory Method pattern from Design Patterns [Gamma95]. The static factory method described in this item has no direct equivalent in Design Patterns.

點選展開中文翻譯