設計模式—組合模式

來源:互聯網
上載者:User

組合模式的英文原文是:Compose objects into tree structures to represent part-whole hiearachies. Composite lets clients treat individual objects and compositions of objects uniformly. 意思是:將對象組合成樹形結構以表示“部分—整體”的階層,使得使用者對單個對象和組合對象的使用具有一致性。

組合模式有三個角色:

抽象構件(component)角色:定義了參加組合對象的共有的方法和屬性。

葉子構件(Leaf)角色:該角色是葉子物件,其下沒有分支,也就是沒有子節點。

數字構件(composite)角色:該角色代表了參加組合的,其下有分支的樹枝對象,它的作用是將樹枝和葉子組合成一個樹形結構,並定義出管理子物件的方法。

組合模式類圖:


各個類對應的實現代碼:

抽象構件的代碼:

package com.zz.composite;/** * 抽象構件介面 * Copyright 2015年4月25日 * created by txxs * all right reserved */public interface Component {public void operation();}

樹枝結構代碼:

package com.zz.composite;import java.util.ArrayList;/** * 定義樹枝構件 * Copyright 2015年4月25日 * created by txxs * all right reserved */public class Composite implements Component {//構件容器private ArrayList<Component> componentList = new ArrayList<Component>();//添加構件public  void add(Component component){this.componentList.add(component);}//刪除構件public void remove(Component component){this.componentList.remove(component);}//擷取子構件public ArrayList<Component>getChild(){return this.getChild();}@Overridepublic void operation() {//商務邏輯代碼}}

葉子結構代碼:

package com.zz.composite;/** * 定義葉子構件 * Copyright 2015年4月25日 * created by txxs * all right reserved */public class Leaf implements Component {@Overridepublic void operation() {//業務員邏輯代碼}}

組合模式的優點:

1、調用簡單,使用者不必關心自己處理的是單個對象還是組合對象。

2、靈活增加節點,想要增加樹枝或者葉子節點只要需要找到父節點即可,不必為了增加對象組件而修改代碼

組合模式適合的情境:

1、描述對象的部分和整體的等級結構。

2、當需要忽略個體組件和組合構件的區別時

源碼下載

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.