Java设计模式《十五》组合模式
来源:互联网 发布:虚拟多点定位软件 编辑:程序博客网 时间:2024/06/15 22:12
//组合模式 将对象组合成树状结构以表示 部分-整体的层次结构//组合模式使用得用户对单个对象和组合对象的使用具有一致性//需求中体现部分与整体层次的机构时//以及希望用户可以忽略组合对象与每个对象的不同 统一使用组合结构中的所有对象时候 可以使用组合模式
//组合中的对象声明接口 在适当的情况下 实现所有类共有接口的默认行为//声明一个接口用户访问和管理component的子部件public abstract class Component{ protected String name; public Component(String name){ this.name=name; } public abstract void add(Component c); public abstract void remove(Component c); public abstract void display(int depth);}//定义支节点行为 可以存储支节点或者叶节点public class Composite extends Component{ private List<Component> children = new ArrayList<Component>(); public Composite(String name){ super(name); } public void add(Component c){ children.add(c); } public void remove(Component c){ children.remove(c); } public void display(int depth){ StringBuilder sb = new StringBuilder(); for(int i=0;i<depth;i++){ sb.append("-"); } System.out.println(); Iterator<Component> iterator = children.iterator(); while(iterator.hasNext()){ ((Component)(iterator.next())).display(depth+2); } }}//定义叶节点行为 不能添加子节点public class Leaf extends Component{ public Leaf(String name){ super(name); } public void add(Component c){ System.out.println("Can not add to leaf"); } public void remove(Component c){ System.out.println("Can not remove leaf"); } public void display(int depth){ StringBuilder sb = new StringBuilder(); for(int i=0;i<depth;i++){ sb.append("-"); } System.out.println(sb.toString()+name); }}
/** * 组合模式,将对象组合成树形结构以表示“部分-整体”的层次结构。 * 组合模式使用得用户对单个对象和组合对象的使用具有一致性。 * * 需求中体现部分与整体层次的结构时, * 以及希望用户可以忽略组合对象与单个对象的不同,统一使用组合结构中的所有对象时,可以使用组合模式。 */public class TestComposite { public static void main(String[] args) { Composite root = new Composite("root"); root.add(new Leaf("Leaf A")); root.add(new Leaf("Leaf B")); Composite comp = new Composite("Composite X"); comp.add(new Leaf("Leaf XA")); comp.add(new Leaf("Leaf XB")); //comp.display(1); root.add(comp); Composite comp2 = new Composite("Composite XY"); comp2.add(new Leaf("Leaf XYA")); comp2.add(new Leaf("Leaf XYB")); comp.add(comp2); root.add(new Leaf("Leaf C")); Leaf leaf = new Leaf("Leaf D"); root.add(leaf); root.remove(leaf); //leaf.add(new Leaf("Leaf E")); root.display(1); }}
0 0
- Java设计模式《十五》组合模式
- 设计模式(十五)---组合模式
- 十五 设计模式之组合模式
- 设计模式C++实现十五:组合模式
- 设计模式(十五)组合模式
- 设计模式—组合模式(十五)
- JAVA设计模式 -- 组合模式
- JAVA设计模式:组合模式
- Java 设计模式-组合模式
- java设计模式-组合模式
- Java设计模式--组合模式
- Java设计模式--组合模式
- Java设计模式----组合模式
- JAVA设计模式(组合模式)
- JAVA设计模式--组合模式
- java设计模式--组合模式
- java设计模式--组合模式
- JAVA 设计模式 组合模式
- java注解解析
- Mac搭建本地svn服务器,并用Cornerstone连接服务器 以及报错Permission denied处理
- 第四次作业
- QTableWidget 用法详解
- 用scanner从键盘输入3个整数,输出最大的值.
- Java设计模式《十五》组合模式
- TeX中的引号
- bzoj 1007
- game
- Java设计模式《十六》迭代器模式
- 剑指offer-面试题39-二叉树的深度
- 第八届蓝桥杯纸牌三角形
- 计算机牛人资料大全
- ORACLE PLSQL代码块学习