国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

java設計模式之組合模式(Composite)

2019-11-26 13:20:40
字體:
來源:轉載
供稿:網友

概述

是一種結構型模式,將對象以樹形結構組織起來,以表示“部分 - 整體”的層次結構,使得客戶端對單個對象和組合對象的使用具有唯一性。

UML類圖

上面的類圖包含的角色:

Component:為參加組合的對象聲明一個公共的接口,不管是組合還是葉節點。
Leaf:在組合中表示葉子結點對象,葉子結點沒有子結點。
Composite:表示參加組合的有子對象的對象,并給出樹枝構建的行為;

代碼示例

import java.util.ArrayList;import java.util.List;abstract class Component {  protected String name;  public Component(String name) {    this.name = name;  }  public abstract void Add(Component c);  public abstract void Remove(Component c);  public abstract void GetChild(int depth);}class Leaf extends Component {  public Leaf(String name) {    super(name);  }  @Override  public void Add(Component c) {    System.out.println("Can not add to a leaf");  }  @Override  public void Remove(Component c) {    System.out.println("Can not remove from a leaf");  }  @Override  public void GetChild(int depth) {    String temp = " ";    for (int i = 0; i < depth; i++) {      temp += "-";      System.out.println(temp + name);    }  }}class Composite extends Component {  private List<Component> children = new ArrayList<>();  public Composite(String name) {    super(name);  }  @Override  public void Add(Component c) {    children.add(c);  }  @Override  public void Remove(Component c) {    children.remove(c);  }  @Override  public void GetChild(int depth) {    for (Component c : children) {      c.GetChild(depth);    }  }}public class Main {  public static void main(String args[]) {    Composite root = new Composite("root");    root.Add(new Leaf("Leaf A"));    root.Add(new Leaf("Leaf B"));    Composite compX = new Composite("Composite X");    compX.Add(new Leaf("Leaf XA"));    compX.Add(new Leaf("Leaf XB"));    root.Add(compX);    Composite compXY = new Composite("Composite XY");    compXY.Add(new Leaf("Leaf XYA"));    compXY.Add(new Leaf("Leaf XYB"));    compX.Add(compXY);    root.GetChild(3);  }}

應用場景

1.要求表示對象的部分-整體層次結構。
2.想要客戶端忽略組合對象與單個對象的差異,客戶端將統一地使用組合結構中的所有對象。

組合模式定義由Leaf對象和Composite對象組成的類結構;
使得客戶端變得簡單;
它使得添加或刪除子部件變得很容易。

 以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 方正县| 双江| 郁南县| 滦平县| 盖州市| 青州市| 武陟县| 太白县| 运城市| 许昌县| 冷水江市| 调兵山市| 新野县| 紫金县| 湘潭市| 江川县| 岑溪市| 五华县| 清徐县| 元阳县| 荆门市| 蓬莱市| 乌恰县| 乐至县| 义乌市| 邵东县| 大英县| 黄大仙区| 滦平县| 桦甸市| 额济纳旗| 勐海县| 柳河县| 平湖市| 铁力市| 清徐县| 正定县| 池州市| 马关县| 固阳县| 宜兰市|