Java 中組合模型之對象結(jié)構(gòu)模式的詳解
Java 中組合模型之對象結(jié)構(gòu)模式的詳解
一、意圖
將對象組合成樹形結(jié)構(gòu)以表示”部分-整體”的層次結(jié)構(gòu)。Composite使得用戶對單個對象和組合對象的使用具有一致性。
二、適用性
你想表示對象的部分-整體層次結(jié)構(gòu)
你希望用戶忽略組合對象與單個對象的不同,用戶將統(tǒng)一使用組合結(jié)構(gòu)中的所有對象。
三、結(jié)構(gòu)

四、代碼
public abstract class Component {
protected String name; //節(jié)點名
public Component(String name){
this.name = name;
}
public abstract void doSomething();
}
public class Composite extends Component {
/**
* 存儲節(jié)點的容器
*/
private List<Component> components = new ArrayList<>();
public Composite(String name) {
super(name);
}
@Override
public void doSomething() {
System.out.println(name);
if(null!=components){
for(Component c: components){
c.doSomething();
}
}
}
public void addChild(Component child){
components.add(child);
}
public void removeChild(Component child){
components.remove(child);
}
public Component getChildren(int index){
return components.get(index);
}
}
public class Leaf extends Component {
public Leaf(String name) {
super(name);
}
@Override
public void doSomething() {
System.out.println(name);
}
}
public class Client {
public static void main(String[] args){
// 構(gòu)造一個根節(jié)點
Composite root = new Composite("Root");
// 構(gòu)造兩個枝干節(jié)點
Composite branch1 = new Composite("Branch1");
Composite branch2 = new Composite("Branch2");
// 構(gòu)造兩個葉子節(jié)點
Leaf leaf1 = new Leaf("Leaf1");
Leaf leaf2 = new Leaf("Leaf2");
branch1.addChild(leaf1);
branch2.addChild(leaf2);
root.addChild(branch1);
root.addChild(branch2);
root.doSomething();
}
}
輸出結(jié)果:
Root
Branch1
Leaf1
Branch2
Leaf2
如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
深入解析Java中的編碼轉(zhuǎn)換以及編碼和解碼操作
這篇文章主要介紹了Java中的編碼轉(zhuǎn)換以及編碼和解碼操作,文中詳細解讀了編碼解碼的相關(guān)IO操作以及內(nèi)存使用方面的知識,需要的朋友可以參考下2016-02-02
使用SpringMVC 重寫、擴展HttpServletRequest請求參數(shù)
這篇文章主要介紹了使用SpringMVC 重寫、擴展HttpServletRequest請求參數(shù),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08
Java TreeMap升序|降序排列和按照value進行排序的案例
這篇文章主要介紹了Java TreeMap升序|降序排列和按照value進行排序的案例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-10-10
詳解SpringBoot 創(chuàng)建定時任務(wù)(配合數(shù)據(jù)庫動態(tài)執(zhí)行)
本篇文章主要介紹了SpringBoot 創(chuàng)建定時任務(wù)(配合數(shù)據(jù)庫動態(tài)執(zhí)行),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-10-10
Springboot+Bootstrap實現(xiàn)增刪改查實戰(zhàn)
這篇文章主要介紹了Springboot+Bootstrap實現(xiàn)增刪改查實戰(zhàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-12-12

