设计模式之Composite模式(笔记)
生活随笔
收集整理的這篇文章主要介紹了
设计模式之Composite模式(笔记)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
組合模式:將對象組合成樹形結(jié)構(gòu)以表示“部分-總體”的層次結(jié)構(gòu)。
組合模式使得用戶對單個(gè)對象和組合對象的使用具有一致性。
適用場合:當(dāng)需求中是體現(xiàn)部分與總體層次的結(jié)構(gòu)時(shí),以及希望用戶能夠忽略組合對象與單個(gè)對象的不同,統(tǒng)一地使用組合結(jié)構(gòu)中的全部對象時(shí),就應(yīng)該考慮用組合模式。
首先定義一個(gè)Componet抽象類
定義葉結(jié)點(diǎn)對象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); } }結(jié)點(diǎn)定義枝結(jié)點(diǎn)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); }結(jié)果:
-root
- - -LeafA
- - -LeafB
- - -Composite X
- - - - -LeafXA
- - - - -LeafXB
- - -Composite Y
- - - - -LeafXYA
- - - - -LeafXYB
- - -LeafC
總結(jié)
以上是生活随笔為你收集整理的设计模式之Composite模式(笔记)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 酷狗铃声如何制作铃声
- 下一篇: HTTP 错误 500.22 - Int