先写一个抽象类,表示一部分public abstract class Component {protected String name;public Comp
先写一个抽象类,表示一部分
public 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);
}
再写叶子节点
public class Leaf extends Component{
public Leaf(String name) {
super(name);
// TODO Auto-generated constructor stub
}
@Override
public void Add(Component c) {
// TODO Auto-generated method stub
System.out.println("不能增加一个片叶子");
}
@Override
public void Remove(Component c) {
// TODO Auto-generated method stub
System.out.println("不能移除一个片叶子");
}
@Override
public void Display(int depth) {
// TODO Auto-generated method stub
for(int i=0;i<depth;i++)
{
System.out.print('-');
}
System.out.println(name);
}
}
import java.util.ArrayList;
import java.util.List;
public class Composite extends Component{
private List<Component> children =new ArrayList<Component>();
public Composite(String name) {
super(name);
// TODO Auto-generated constructor stub
}
@Override
public void Add(Component c) {
// TODO Auto-generated method stub
children.add(c);
}
@Override
public void Remove(Component c) {
// TODO Auto-generated method stub
children.remove(c);
}
@Override
public void Display(int depth) {
// TODO Auto-generated method stub
for(int i=0;i<depth;i++)
{
System.out.print('-');
}
System.out.println(name);
for (Component component : children) {
component.Display(depth+2);;
}
}
}
在写测试类
public class Program {
public static void main(String[] args) {
// TODO Auto-generated method stub
Composite root = new Composite("root");
root.Add(new Leaf("Leaf A"));
root.Add(new Leaf("Leaf B"));
Composite composite = new Composite("Composite X");
composite.Add(new Leaf("Leaf XA"));
composite.Add(new Leaf("Leaf XB"));
root.Add(composite);
Composite composite2 = new Composite("Composite XY");
composite2.Add(new Leaf("Leaf XYA"));
composite2.Add(new Leaf("Leaf XYB"));
composite.Add(composite2);
root.Add(new Leaf("Leaf C"));
Leaf leaf =new Leaf("Leaf D");
root.Add(leaf);
root.Remove(leaf);
root.Display(1);
}
}