Try   HackMD

六角鼠年鐵人賽 Week 40 - Design Pattern - Composite/Aggregate Reuse Principle

大家好,我是 "為了拿到金角獎盃而努力著" 的文毅青年 - Kai

王雪红

要成功,就得做最困難的事

前引

是否覺得有些時候不是那麼需要使用繼承的方式處理類方法的取用?
是否覺得能夠分開類後再組合一起遠比繼承簡單明瞭?

那你需要的就是 Composite/Aggregate Reuse Principle 的概念!

主題

終於來到了物件導向設計原則最後一條 Composite/Aggregate Reuse Principle

中文常見名稱 合成/聚合複用原則

Composite/Aggregate Reuse Principle 意即採取繼承或介面實現以前,先考慮使用合成、聚合的方式處理關聯關係。

就以上一篇的實例往下說,如果今天針對 Report 的部分尚有分成了

  • Daily Report
  • Weekly Report
  • Monthly Report
  • Quartly Report
  • Yearly Report
    呢?

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

應該不會有人想要為每一個不同的 Report 再去加寫不同的實現類別出來吧

參考的作法應改為建立新的 Report 介面類別,然後建立許多實現類別去實現這個介面,接著把 Report 介面類別聚合到各職務的介面類別中 (Manager Interface, Engineer Interface, Saler Interface)

這樣各職務實現類不需要為了 Report 的種類還做出更多不同實現類了!

Kai 會以這例子做一個圖片放在下面讓大家看明白,不擔心!

先來了解一下實際上對於設計架構的幫助!

幫助

  • 維持類別的封裝特性
  • 聚合與被聚合的類別有著低耦合的特性,降低擴展時的難易度
  • 提高聚合與被聚合的類別在動態處理的靈活性

實例

  • 參考了第 39 篇取出部分的圖

    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →

  • 如果加上一堆 Report 的實現類別則會變成如下,看起來非常怪異

    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →

  • 若把 Report 獨立成一個類,聚合進 Manager 的介面類當中,則可以避免採取多實現類的方式,同時避免高偶合的狀況。

    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →

又過了一週,又學習到一個新的 Principle,希望大家都能與 Kai 一起慢慢把基本功紮實起來吧!

首頁 Kai 個人技術 Hackmd

tags: Design Pattern,w3HexSchool