設計模式:合成模式

來源:互聯網
上載者:User

標籤:設計模式   合成模式   

原文地址:http://leihuang.org/2014/12/09/composite/


Structural 模式 如何設計物件之間的靜態結構,如何完成物件之間的繼承、實 現與依賴關係,這關乎著系統設計出來是否健壯(robust):像是易懂、易維護、易修改、耦合度低等等議題。Structural 模式正如其名,其分類下的模式給出了在不同場合下所適用的各種物件關係結構。

  • Default Adapter 模式
  • Adapter 模式
  • Bridge 模式
  • Composite 模式
  • Decorator 模式
  • Facade 模式
  • Flyweight 模式
  • Proxy 模式

Composite模式是構造型的設計模式之一,通過遞迴手段來構造諸如檔案系統之類的樹形的對象結構;Composite模式所代表的資料構造是一群具有統一介面介面的對象集合,並可以通過一個對象來訪問所有的對象(遍曆)。

舉個例子,比如一棵樹包括樹枝和樹葉,樹枝上面又有樹枝和樹葉,這樣一直迴圈下去...如

假如讓你實現一棵樹,你會不會把每一個樹枝都給定義出來?肯定不會.那麼這就需要用到組合模式.組合模式基本結構如.

我們現在就利用組合模式來實現,這棵樹.

IBranch 介面

public interface IBranch {    public void print() ;}

Leaf 類

public class Leaf implements IBranch {    private String leaf = null ;    public Leaf(String leaf){        this.leaf = leaf ;    }    @Override    public void print() {        System.out.println(leaf);    }}

BranchComposite 類

import java.util.LinkedList;import java.util.List;public class BranchComposite implements IBranch {    private List<IBranch> branchList = null ;    public BranchComposite(){        branchList = new LinkedList<IBranch>() ;    }    public void add(IBranch branch){        branchList.add(branch) ;    }    public boolean remove(IBranch branch){        return branchList.remove(branch) ;    }    @Override    public void print() {        for(IBranch branch : branchList){            branch.print();        }    }}

Client 類

public class Client {    public static void main(String[] args) {        IBranch leaf1 = new Leaf("leaf 1") ;        IBranch leaf2 = new Leaf("leaf 2") ;        IBranch leaf3 = new Leaf("leaf 3") ;        BranchComposite branch0 = new BranchComposite() ;        BranchComposite branch1 = new BranchComposite() ;        BranchComposite branch2 = new BranchComposite() ;        branch0.add(leaf1);        branch0.add(branch1);        branch1.add(leaf2);        branch1.add(branch2);        branch2.add(leaf3);        //branch0.print() ;        //branch1.print() ;        //branch2.print() ;    }}

2014-12-09 17:09:18

Brave,Happy,Thanksgiving !


設計模式:合成模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.