组合模式原理:将对象组合成树形结构以表示“部分-整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。组合模式包括的成员角色有:
树干(Component):组合中的对象声明接口,在适当情况下,实现所有类共有接口的默认行为。声明一个接口用于访问和管理Component的子部件。
树枝(Composite):定义有枝节点行为,用来存储子部件,在Component接口中实现与子部件有关的操作,比如增加删除。
叶子(Leaf):在组合中表示叶节点对象,叶节点没有子节点。
UML图如下:
代码如下:
Component 部分:
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);
}
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);
}
Leaf 部分:
class Leaf
extends Component {
public Leaf(String name) {
super(name);
}
@Override
public void Add(Component c) {
System.out.println("Can not add to a leaf");
}
@Override
public void Remove(Component c) {
System.out.println("Can not remove from a leaf");
}
@Override
public void Display( int depth) {
String temp = "";
for ( int i = 0; i < depth; i++)
temp += '-';
System.out.println(temp + name);
}
}
public Leaf(String name) {
super(name);
}
@Override
public void Add(Component c) {
System.out.println("Can not add to a leaf");
}
@Override
public void Remove(Component c) {
System.out.println("Can not remove from a leaf");
}
@Override
public void Display( int depth) {
String temp = "";
for ( int i = 0; i < depth; i++)
temp += '-';
System.out.println(temp + name);
}
}
Composite 部分:
class Composite
extends Component {
private List<Component> children = new ArrayList<Component>();
public Composite(String name) {
super(name);
}
@Override
public void Add(Component c) {
children.add(c);
}
@Override
public void Remove(Component c) {
children.remove(c);
}
@Override
public void Display( int depth) {
String temp = "";
for ( int i = 0; i < depth; i++)
temp += '-';
System.out.println(temp + name);
for (Component c : children) {
c.Display(depth + 2);
}
}
}
private List<Component> children = new ArrayList<Component>();
public Composite(String name) {
super(name);
}
@Override
public void Add(Component c) {
children.add(c);
}
@Override
public void Remove(Component c) {
children.remove(c);
}
@Override
public void Display( int depth) {
String temp = "";
for ( int i = 0; i < depth; i++)
temp += '-';
System.out.println(temp + name);
for (Component c : children) {
c.Display(depth + 2);
}
}
}