2011年4月13日 星期三

Gof Creational - Facade Pattern


  • Intent


提供一個單一且盡可能簡化的介面給client端存取各項自系統,常見的應用是J2EE Session Facade,而事實上在前面其他的章節中看到的 Abstract Factory就是一種Facade pattern的實做。


常見的狀況是,在client端直接的呼叫了business object的各項功能,這樣的情況下導致client端必須很清楚的知道整個商業流程細節,以及必須細心的維護每一次系統需求調整時,相應的business object 的呼叫方式甚至順序,這樣的狀況會使得程式在維護時,變得很難以控制,不小心就變成了大爆炸。


在自己的經驗中,過去寫過一個複雜的查詢功能程式,在jsp中我 寫了 html , javascript , scriptlets , ejb call interactions ..,寫到後來還因為要夾雜script與html輸出,在scriptlets中做了更多苦工,而這樣的code,就被我資深同事給打槍,他接手時選擇整個砍掉重練,完全不理會我原本的功能是寫啥了XD ( Orz...這打擊真大...)


所以,真的要好好善用facade,對於前端的程式碼,盡可能地不該相依於後端的business obj ,如此面臨功能變動時,異動影響的範圍就少了很多。




  • Benefits




  1. 在不影響既有的各項子系統提供的操作功能中,提供一個簡單的介面給予操作。

  2. 屏蔽了各項子系統的複雜內容。

  3. 同時也因為透過單一物件的傳遞資訊,降低了cleint與各項子系統的耦合度。




  • 適用情境


1. You need to provide a simple interface to a complex subsystem.

2. Several dependencies exist between clients and the implementation classes of an abstraction.

3. Layering the subsystems is necessary or desired.


  • 常見的Lib or API - java.net.URL

  • (Force) How to ?




  • Provide a simpler interface to the clients by hiding all the complex interactions between business components.

  • Reduce the number of business objects that are exposed to the client across the service layer over the network.

  • Hide from the client the underlying interactions and interdependencies between business components. This provides better manageability, centralization of interactions (responsibility), greater flexibility, and greater ability to cope with changes.

  • Provide a uniform coarse-grained service layer to separate business object implementation from business service abstraction.

  • Avoid exposing the underlying business objects directly to the client to keep tight coupling between the two tiers to a minimum.

  • Use a session bean as a facade to encapsulate the complexity of interactions between the business objects participating in a workflow. The Session Facade manages the business objects, and provides a uniform coarse-grained service access layer to clients.




  • Class Diagram



  • [caption id="attachment_196" align="alignnone" width="478" caption="SessionFacade"]SessionFacade[/caption]

沒有留言: