l

2012年10月22日 星期一

尋找Force實驗6:Singleton篇

Oct. 18 22:46~23:15

image

***

今天來找Singleton pattern的Force,依照慣例先把Intent改成Problem。

Intent

Ensure a class only has one instance, and provide a global point of access to it.

這一整句感覺像是solution。其實Teddy在《Creational Patterns要解決什麼問題(上)?》已經提到,這些creational pattern的Problem都可以寫成:

Problem:How do you create an object?

中文:你如何產生一個物件?

接下來看一下GoF書中Singleton pattern的Motivation,看看能不能找到Force或是其他東西。

Motivation

It's important for some classes to have exactly one instance. Although there can be many printers in a system, there should be only one printer spooler. There should be only one file system and one window manager. A digital filter will have one A/D converter. An accounting system will be dedicated to serving one company.

How do we ensure that a class has only one instance and that the instance is easily accessible? A global variable makes an object accessible, but it doesn't keep you from instantiating multiple objects.

第一段標示為藍色的字,看起來像是Force。第二段標示為藍色的字,本身就是一個問句,也很像Problem,也可以是Force。

Force 1: The property of having only one instance of class is a property of the type being represented, such as a class that realizes a stateful API to a specific piece of hardware in a system, and not simply an incidental property of an application that uses only a single instance of a class. (這一句是從 POSA 5 節錄出來的)

Force 2: The sole instance should be easily accessible.

繼續看下去。

A better solution is to make the class itself responsible for keeping track of its sole instance. The class can ensure that no other instance can be created (by intercepting requests to create new objects), and it can provide a way to access the instance. This is the Singleton pattern.

以上這段算是在說明Solution。

***

最後看一下Applicability。

Applicability

  • there must be exactly one instance of a class, and it must be accessible to clients from a well-known access point.
  • when the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code.

***

Applicability好像沒什麼影響,所以之前找到的Force是最後的結果。最後把剛剛寫出的Problem列與Force出來:

Problem: How do you create an object?

Force:

  • The property of having only one instance of class is a property of the type being represented, such as a class that realizes a stateful API to a specific piece of hardware in a system, and not simply an incidental property of an application that uses only a single instance of a class.
  • The sole instance should be easily accessible.

***

找完收工。

***

友藏內心獨白:《Creational Patterns要解決什麼問題》的下集怎麼一直沒寫出來?

沒有留言:

張貼留言