l

2010年6月22日 星期二

Program to an interface

06/22 22:00~23:20

看過 Design Patterns 這本書的人,一定會記得第18頁的這一句至理名言:

Program to an interface, not an implementation.

讓我們看一下書中這一句的前後文:

There are two benefits to manipulating objects solely in terms of the interface defined by abstract classes:
  1. Clients remain unaware of the specific types of objects they use, as long as the objects adhere to the interface that clients expect.
  2. Clients remain unaware of the classes that implement these objects. Clients only know about the abstract class(es) defining the interface.
This so greatly reduces implementation dependencies between subsystems that it leads to the following principle of reusable object-oriented design:

Program to an interface, not an implementation.

Don't declare variables to be instances of particular concrete classes. Instead, commit only to an interface defined by an abstract class.

先用白話文解釋一下這句話,假設鄉民們要幫公司在資訊展上面找 show girls 站台,物件導向技術學得好的人就知道要符合『program to an interface』的精神來開出條件給公關公司找人。

有酷似『豆花妹』甜美的笑容,媲美『遙遙』殺很大的身材,外加『林志玲』的娃娃音。

這樣子應該很容易可以找到一票符合條件的 show girls。反之,如果是『program to an implementation』,就會變成:

 我要『豆花妹』,『遙遙』,外加『林志玲』。

都已經『指名購買』了,再怎麼找全台灣也就是這三個人。萬一當天有人臨時生病,可是連個替代人選都沒有(implementation dependencies)。

所以,program to an interface 的好處就很明顯了:

  • 不管黑貓,白貓,只要能抓老鼠的(符合 interface)就是好貓。也就是說,可選擇性變多了,不會被綁死在某一個人或是品牌上面。
  • 有一天發現世界上有一種比黑貓和白貓更厲害的『熊貓』,只要符合介面直接換掉程式都不用改。

結論:Thinking about what you can do rather than who you are.

***

友藏內心獨白:最難的就是定義 interfaces 啦。

沒有留言:

張貼留言