當(dāng)前位置:
首頁 >
Java 之 合成模式
發(fā)布時間:2025/3/17
36
豆豆
生活随笔
收集整理的這篇文章主要介紹了
Java 之 合成模式
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
2019獨(dú)角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
public interface Component {public void printStruct(String preStr); }public class Leaf implements Component {/*** 葉子對象的名字*/private String name;/*** 構(gòu)造方法,傳入葉子對象的名稱* * @param name* 葉子對象的名字*/public Leaf(String name) {this.name = name;}/*** 輸出葉子對象的結(jié)構(gòu),葉子對象沒有子對象,也就是輸出葉子對象的名字* * @param preStr* 前綴,主要是按照層級拼接的空格,實(shí)現(xiàn)向后縮進(jìn)*/@Overridepublic void printStruct(String preStr) {// TODO Auto-generated method stubSystem.out.println(preStr + "-" + name);}} public class Composite implements Component {/*** 用來存儲組合對象中包含的子組件對象*/private List<Component> childComponents = new ArrayList<Component>();/*** 組合對象的名字*/private String name;/*** 構(gòu)造方法,傳入組合對象的名字* * @param name* 組合對象的名字*/public Composite(String name) {this.name = name;}/*** 聚集管理方法,增加一個子構(gòu)件對象* * @param child* 子構(gòu)件對象*/public void addChild(Component child) {childComponents.add(child);}/*** 聚集管理方法,刪除一個子構(gòu)件對象* * @param index* 子構(gòu)件對象的下標(biāo)*/public void removeChild(int index) {childComponents.remove(index);}/*** 聚集管理方法,返回所有子構(gòu)件對象*/public List<Component> getChild() {return childComponents;}/*** 輸出對象的自身結(jié)構(gòu)* * @param preStr* 前綴,主要是按照層級拼接空格,實(shí)現(xiàn)向后縮進(jìn)*/@Overridepublic void printStruct(String preStr) {// 先把自己輸出System.out.println(preStr + "+" + this.name);// 如果還包含有子組件,那么就輸出這些子組件對象if (this.childComponents != null) {// 添加兩個空格,表示向后縮進(jìn)兩個空格preStr += " ";// 輸出當(dāng)前對象的子對象for (Component c : childComponents) {// 遞歸輸出每個子對象c.printStruct(preStr);}}} }public class Client {public static void main(String[] args) {Composite root = new Composite("服裝");Composite c1 = new Composite("男裝");Composite c2 = new Composite("女裝");Leaf leaf1 = new Leaf("襯衫");Leaf leaf2 = new Leaf("夾克");Leaf leaf3 = new Leaf("裙子");Leaf leaf4 = new Leaf("套裝");root.addChild(c1);root.addChild(c2);c1.addChild(leaf1);c1.addChild(leaf2);c2.addChild(leaf3);c2.addChild(leaf4);root.printStruct("");} }學(xué)習(xí)設(shè)計模式強(qiáng)烈推薦的博客:java_my_life
代碼地址:lennon
轉(zhuǎn)載于:https://my.oschina.net/u/1589819/blog/1561005
總結(jié)
以上是生活随笔為你收集整理的Java 之 合成模式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Verilog hdl 宏定义编译报错
- 下一篇: Javascript实现计数器,定时警告