日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

设计模式之Composite模式(笔记)

發布時間:2023/12/31 asp.net 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 设计模式之Composite模式(笔记) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

組合模式:將對象組合成樹形結構以表示“部分-總體”的層次結構。

組合模式使得用戶對單個對象和組合對象的使用具有一致性。
適用場合:當需求中是體現部分與總體層次的結構時,以及希望用戶能夠忽略組合對象與單個對象的不同,統一地使用組合結構中的全部對象時,就應該考慮用組合模式。



首先定義一個Componet抽象類

public abstract class Component {protected String name;public Component(String name){this.name=name;}//抽象方法public abstract void add(Component c);public abstract void delete(Component c);public abstract void dispaly(int depth); }

定義葉結點對象Leaf,繼承Componet

public class Leaf extends Component {public Leaf(String name) {super(name);}@Overridepublic void add(Component c) {System.out.println("can not add a leaf");}@Overridepublic void delete(Component c) {System.out.println("can not delete a leaf");}@Overridepublic void dispaly(int depth) {char[] ch=new char[depth];for(int i=0;i<depth;i++){ch[i]='-';}System.out.println(new String(ch)+name); } }

結點定義枝結點Composite繼承Component

public class Composite extends Component{private List<Component> children=new ArrayList<Component>();public Composite(String name) {super(name);}@Overridepublic void add(Component c) {children.add(c);}@Overridepublic void delete(Component c) {children.remove(c);}@Overridepublic void dispaly(int depth) {char[] ch=new char[depth];for(int i=0;i<depth;i++){ch[i]='-';}System.out.println(new String(ch)+name);Iterator<Component> iterator=children.iterator();while(iterator.hasNext()){Component component=iterator.next();component.dispaly(depth+2);}}}

client代碼

public static void main(String[] args) {//組合模式Composite root=new Composite("root");root.add(new Leaf("LeafA"));root.add(new Leaf("LeafB"));Composite comp=new Composite("Composite X");comp.add(new Leaf("LeafXA"));comp.add(new Leaf("LeafXB"));root.add(comp);Composite comp2=new Composite("Composite Y");comp2.add(new Leaf("LeafXYA"));comp2.add(new Leaf("LeafXYB"));root.add(comp2);root.add(new Leaf("LeafC"));root.dispaly(1); }

結果:
-root
- - -LeafA
- - -LeafB
- - -Composite X
- - - - -LeafXA
- - - - -LeafXB
- - -Composite Y
- - - - -LeafXYA
- - - - -LeafXYB
- - -LeafC

總結

以上是生活随笔為你收集整理的设计模式之Composite模式(笔记)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。