[实验任务一]:组合模式
用透明组合模式实现教材中的“文件夹浏览”这个例子。
1.类图

2. 源代码
public abstract class Component { private String name = ""; public Component(String name){ this.name = name; } protected String getName(){ return name; } protected abstract void printStruct(String prefix); /** * 向组合对象中加入组件对象 * 叶子对象没有该功能 * * */ protected void addChild(Component component) { throw new UnsupportedOperationException("此对象不支持addChild该功能"); } /** * 向组合对象中移除组件对象 * 叶子对象没有该功能 * * */ protected void removeChild(Component component){ throw new UnsupportedOperationException("此对象不支持removeChild该功能"); } }
public class Leaf extends Component { public Leaf(String name){ super(name); } /*** * 打印对应的叶子结构 * @param prefix 前缀 实现向后缩进 * */ public void printStruct(String prefix){ System.out.println(prefix + "-" + super.getName()); } }
public class Composite extends Component{ List<Component> componentList = new ArrayList<>(); public Composite(String name) { super(name); } @Override protected void printStruct(String prefix) { System.out.println(prefix + "+" + getName()); if (componentList != null) { //打印其叶子节点,缩进一个空格 for(Component component: componentList) { component.printStruct(prefix + prefix); } } } @Override protected void addChild(Component component) { this.componentList.add(component); } @Override protected void removeChild(Component component) { this.componentList.remove(component); } }
public class Client { public static void main(String[] args) { //组合对象 作为根节点 Component root = new Composite("服装"); //组合对象 Component composite1 = new Composite("夏装"); Component composite2 = new Composite("冬装"); //叶子节点 Leaf leaf1 = new Leaf("裙子"); Leaf leaf2 = new Leaf("背心"); Leaf leaf3 = new Leaf("棉衣"); root.addChild(composite1); root.addChild(composite2); composite1.addChild(leaf1); composite1.addChild(leaf2); composite2.addChild(leaf3); root.printStruct(""); } }

浙公网安备 33010602011771号