设计模式之---组合模式

来源:互联网 发布:阿里云服务器ecs备份 编辑:程序博客网 时间:2024/06/06 20:57

组合模式

是最常用的一种数据结构了,组合模式就将这种数据结构用到类的组合上。

package composite;public abstract class Component {protected String name;public Component(String name) {super();this.name = name;}public abstract void add(Component component);public abstract void removeChildren(Component component);public abstract void show(int depth);}
package composite;import java.util.ArrayList;import java.util.List;public class Composite extends Component {private List<Component> children=new ArrayList<>();public Composite(String name) {super(name);// TODO Auto-generated constructor stub}@Overridepublic void add(Component component) {// TODO Auto-generated method stubchildren.add(component);}@Overridepublic void removeChildren(Component component) {// TODO Auto-generated method stubchildren.remove(component);}@Overridepublic void show(int depth) {// TODO Auto-generated method stubfor(int i=0;i<depth;i++)System.out.print("-");System.out.println("Composite: " + name);for(Component component:children) {component.show(depth+1);}}}
package composite;public class Leaf extends Component {public Leaf(String name) {super(name);// TODO Auto-generated constructor stub}@Overridepublic void add(Component component) {// TODO Auto-generated method stubSystem.out.println("叶子结点不能增加子节点");}@Overridepublic void removeChildren(Component component) {// TODO Auto-generated method stubSystem.out.println("叶子结点无子节点");}@Overridepublic void show(int depth) {// TODO Auto-generated method stubfor(int i=0;i<depth;i++)System.out.print("-");System.out.println("Leaf: " + name);}}
package composite;public class Client {public static void main(String[] args) {// TODO Auto-generated method stubComponent root=new Composite("root");Component leftchild=new Composite("left child");Component rightchild=new Composite("right child");root.add(leftchild);root.add(rightchild);Component leafA=new Leaf("leaf A");Component leafB=new Leaf("leaf B");leftchild.add(leafA);  leftchild.add(leafB);root.show(1);System.out.println();leftchild.removeChildren(leafB);  root.removeChildren(rightchild);root.show(1);}}
运行结果

-Composite: root
--Composite: left child
---Leaf: leaf A
---Leaf: leaf B
--Composite: right child


-Composite: root
--Composite: left child
---Leaf: leaf A

透明方式与安全方式


1 0
原创粉丝点击