设计模式之组合模式
Posted emoji-emoji
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式之组合模式相关的知识,希望对你有一定的参考价值。
组合模式:将对象组合成树形结构以表示“部分-整体”的层次结构。组合模式可以使用户对单个对象和组合对象的使用具有一致性。
public abstract class Component { protected String name; public Component(String name) { this.name = name; } public abstract void add(Component component); public abstract void remove(Component component); public abstract void show(int stamp); }
public class Leaf extends Component { public Leaf(String name) { super(name); } @Override public void add(Component component) { throw new UnsupportedOperationException("不支持该操作。"); } @Override public void remove(Component component) { throw new UnsupportedOperationException("不支持该操作。"); } @Override public void show(int stamp) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < stamp; i++) { builder.append("-"); } System.out.println(builder + name); } }
public class Composite extends Component { private List<Component> child = new ArrayList<>(); public Composite(String name) { super(name); } @Override public void add(Component component) { child.add(component); } @Override public void remove(Component component) { child.remove(component); } @Override public void show(int stamp) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < stamp; i++) { builder.append("-"); } System.out.println(builder + name); for (Component component : child) { component.show(stamp + 2); } } }
public class CompositeDemo { public static void main(String[] args) { Composite root = new Composite("root"); root.add(new Leaf("AA")); root.add(new Leaf("BB")); root.show(1); } }
以上是关于设计模式之组合模式的主要内容,如果未能解决你的问题,请参考以下文章