23种设计模式 第二部分 结构模式(6)组合模式

来源:互联网 发布:ubuntu 虚拟终端 编辑:程序博客网 时间:2024/05/29 16:56


理解

组合模式有时又叫部分-整体模式在处理类似树形结构的问题时比较方便。


实现

import java.util.Enumeration;import java.util.Vector;public class TreeNode {private String name;private TreeNode parent;private Vector<TreeNode> children = new Vector<TreeNode>();public TreeNode(String name){this.name = name;}public String getName() {return name;}public void setName(String name) {this.name = name;}public TreeNode getParent() {return parent;}public void setParent(TreeNode parent) {this.parent = parent;}public void add(TreeNode node){children.add(node);}public void remove(TreeNode node){children.remove(node);}public Enumeration<TreeNode> getChildren(){return children.elements();}}
public class Tree {TreeNode root = null;public Tree(String name){root = new TreeNode(name);}public static void main(String[] args){Tree tree = new Tree("A");TreeNode nodeB = new TreeNode("B");TreeNode nodeC = new TreeNode("C");nodeB.add(nodeC);tree.root.add(nodeB);System.out.println("build the tree");}}
使用场景:将多个对象组合在一起进行操作,常用于表示树形结构中,例如二叉树,数等。

维基百科

The composite pattern is a partitioning design pattern. The composite pattern describes that a group of objects is to be treated in the same wayas a single instance of an object.

=== Java ===<source lang=java>/** "Component" */interface Graphic {    //Prints the graphic.    public void print();}/** "Composite" */import java.util.List;import java.util.ArrayList;class CompositeGraphic implements Graphic {    //Collection of child graphics.    private List<Graphic> childGraphics = new ArrayList<Graphic>();    //Prints the graphic.    public void print() {        for (Graphic graphic : childGraphics) {            graphic.print();        }    }    //Adds the graphic to the composition.    public void add(Graphic graphic) {        childGraphics.add(graphic);    }    //Removes the graphic from the composition.    public void remove(Graphic graphic) {        childGraphics.remove(graphic);    }}/** "Leaf" */class Ellipse implements Graphic {    //Prints the graphic.    public void print() {        System.out.println("Ellipse");    }}/** Client */public class Program {    public static void main(String[] args) {        //Initialize four ellipses        Ellipse ellipse1 = new Ellipse();        Ellipse ellipse2 = new Ellipse();        Ellipse ellipse3 = new Ellipse();        Ellipse ellipse4 = new Ellipse();        //Initialize three composite graphics        CompositeGraphic graphic = new CompositeGraphic();        CompositeGraphic graphic1 = new CompositeGraphic();        CompositeGraphic graphic2 = new CompositeGraphic();        //Composes the graphics        graphic1.add(ellipse1);        graphic1.add(ellipse2);        graphic1.add(ellipse3);        graphic2.add(ellipse4);        graphic.add(graphic1);        graphic.add(graphic2);        //Prints the complete graphic (four times the string "Ellipse").        graphic.print();    }}</source><span style="color:#3333ff;"></span>







0 0
原创粉丝点击