组合模式例子

来源:互联网 发布:纯文字mud游戏编程 编辑:程序博客网 时间:2024/05/16 23:33

一、概述

组合模式(Composite),将对象组合成树形结构来表现“整体&部分”这一层次结构。这种模式能让客户以一致的方式处理个别对象以及对象组合。

二、设计角色

(1)抽象构件角色(Component):是组合中的对象声明接口,在适当的情况下,实现所有类共有接口的默认行为。这个接口可以用来管理所有的子对象。
(2)树枝构件角色(Composite):定义有子部件的那些部件的行为。在Component接口中实现与子部件有关的操作,构件和构件之间是可以嵌套的。
(3)树叶构件角色(Leaf):在组合树中表示叶节点对象,叶节点没有子节点。并在组合中定义图元对象的行为。
(4)客户角色(Client):通过component接口操纵组合部件的对象。

三、UML类图

这里写图片描述

例子:

/* * 抽象构件角色:是树枝构件角色和树叶构件角色是共同抽象 */public abstract class Component {    public abstract void display(int depth);    //添加构件          public void add(Component component){};    //删除构件    public void remove(Component component){};}/* * 组件构件类 */public class Composite extends Component{    private String name;    private List<Component> ComponentList;    public Composite(String name) {        this.name = name;        this.ComponentList = new ArrayList<Component>();    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    @Override    public void display(int depth) {        StringBuffer strBuf = new StringBuffer("");          for (int i = 0; i < depth; i++) {              strBuf.append("--");           }          System.out.println(new String(strBuf) + this.getName());          for (Component c : ComponentList) {              //递归显示            c.display(depth + 2);          }      }    @Override    public void add(Component component) {        ComponentList.add(component);    }    @Override    public void remove(Component component) {        ComponentList.remove(component);    }}/* * 叶子构件类 */public class Leaf extends Component{    private String name;    public Leaf(String name) {        this.name = name;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    @Override    public void display(int depth) {        StringBuilder sb = new StringBuilder("");          for (int i = 0; i < depth; i++) {              sb.append("--");           }          System.out.println(new String(sb) + this.getName() ) ;       }    @Override    public void add(Component component) {        System.out.println("叶子节点不能添加构件...");    }    @Override    public void remove(Component component) {        System.out.println("叶子节点不能删除构件...");    }}/* * 客户端 */public class App {    public static void main(String[] args) {        Composite com1 = new Composite("树枝1");        Leaf leaf1 = new Leaf("树叶1");        Composite com11 = new Composite("树枝1.1");        Leaf leaf11 = new Leaf("树叶1.1");        com1.add(leaf1);        com1.add(com11);        com11.add(leaf11);        com1.display(0);    }}

这里写图片描述

0 0
原创粉丝点击