Design Pattern: Structural Patterns — Composite Pattern (組合模式)

Charlie Lee
Bucketing
Published in
3 min readMay 2, 2020

--

不要再單純的使用For迴圈了,讓你的物件有抽象的組裝概念,他們會自己遞迴自己

Photo by Quino Al on Unsplash

前言

Wiki對於 Composite Pattern的定義如下:

The Composite [2] design pattern is one of the twenty-three well-known GoF design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.

定議提到的組合模式引入可以帶來,更方便的實作、改變、測試和重用,而這些好處在介紹完範例後,再逐步分析。

類別圖

組合模式基本概念

  • 將組合模式中的每個物件都定義成 “is a”
  • 每個物件都會記成Component抽象類別
  • 基本物件會被定義成Leaf
  • Composite包裝Leaf,當作一個Leaf的集合
  • Composite會逐步的訪問每個包裝在內的子物件

範例

英雄遊戲,今天角色發展差不多了,需要開始讓玩家有更多的互動,所以老闆想到了戰團系統,而每個戰團都是由小隊組成(因為工城戰這樣比較好指揮)。看來這個新的系統設計非常適合剛剛學到的Composite Pattern,戰團(Composite)而小隊(Component),那開始設計吧。

  • 創立群組(Group)概念,因為聯盟和小隊都是一個群組
  • 將小隊包裝進聯盟裡
  • 當要使用聯盟時,小隊就會逐步的被使用到

原始碼

結論

Composite Pattern適合用在想將Has a -> Is a的過程

其實在學這個Pattern時,一直覺得為何不好好設一個ArrayList,要使用它的時候從裡面找就好了。

  • 如果上面的範例隊伍要在分為大隊、中隊和小隊,那只要再擴增物件就好
  • 但是如果是用ArrayList則可能要改寫原本物件的架構

--

--