package com.zwy;
import java.util.ArrayList;
import java.util.List;
/*组合模式:
* 组合模式就是:一颗树,树上有节点和叶子,节点下面可以拓展节点,但是叶子不能够在拓展
*
*
* 定义:组合模式:将对象组合成属性结构以表示:"部分整体"的层次结构,组合模式使得用户对单个对象和组合对象
* 的使用具有一致性。
* 当我们发现需求中是体现部分和整体层次的结构是,以及你希望用户可以忽略组合对象和单个对象的不同,同一的使用组合结构中的所有对象就应该考虑使用组合模式了.
* */
public class CompositionTest {
public static void main(String[] args) {
Node root = new ComNode("根节点",0);
root.Add(new Leaf("叶节点1",1));
root.Add(new Leaf("叶节点2",1));
root.Add(new Leaf("叶节点3",1));
Node node1 = new ComNode("节点1", 1);
node1.Add(new Leaf("叶节点4",2));
root.Add(node1);
root.Add(node1);
root.Display();
}
}
class Node {
protected String name ;
protected int depth ;
public Node(String name, int depth){
this.name = name;
this.depth = depth;
}
public void Add(Node node) {
};
public void Remove(Node node) {
};
public void Display() {
};
}
class ComNode extends Node {
protected List<Node> list = null;
public ComNode(String name, int depth) {
super(name, depth);
list = new ArrayList<Node>();
}
@Override
public void Add(Node node) {
list.add(node);
}
@Override
public void Remove(Node node) {
list.remove(node);
}
@Override
public void Display() {
// System.out.println(this.name + ":" + this.depth);
for(int i = 0 ; i < this.depth;i++){
System.out.print("--");
}
System.out.println(this.name + ":" + this.depth);
for(Node node : list){
node.Display();
}
}
}
class Leaf extends Node {
public Leaf(String name, int depth) {
super(name, depth);
}
@Override
public void Display() {
for(int i = 0 ; i < this.depth;i++){
System.out.print("--");
}
System.out.println(this.name + ":" + this.depth);
}
}