设计模式之Composite模式(笔记)
生活随笔
收集整理的這篇文章主要介紹了
设计模式之Composite模式(笔记)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
組合模式:將對象組合成樹形結構以表示“部分-總體”的層次結構。
組合模式使得用戶對單個對象和組合對象的使用具有一致性。
適用場合:當需求中是體現部分與總體層次的結構時,以及希望用戶能夠忽略組合對象與單個對象的不同,統一地使用組合結構中的全部對象時,就應該考慮用組合模式。
首先定義一個Componet抽象類
定義葉結點對象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模式(笔记)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 酷狗铃声如何制作铃声
- 下一篇: 还是时间惹的祸