/**
*
*/
package com.wangbiao.design.composite;
import java.util.ArrayList;
import java.util.List;
/**
* @Title: Component.java
* @Package com.wangbiao.design.composite
* @Description: TODO
* @author wangbiao
* @date 2014-9-28 上午9:50:26
* @version V1.0
*/
public abstract class Component {
String name = null;
public Component(String name) {
this.name = name;
}
public abstract void add(Component component);
public abstract void remove(Component component);
public abstract void display();
}
class Reaf extends Component{
public Reaf(String name) {
super(name);
}
@Override
public void add(Component component) {
// not applicable for Reaf
System.out.println("Not applicable for Reaf");
}
@Override
public void remove(Component component) {
// not applicable for Reaf
System.out.println("Not applicable for Reaf");
}
@Override
public void display() {
System.out.println("Reaf: "+ name);
}
}
class Composite extends Component{
private List list = new ArrayList();
public Composite(String name) {
super(name);
}
@Override
public void add(Component component) {
list.add(component);
}
@Override
public void remove(Component component) {
list.remove(component);
}
@Override
public void display() {
for (Component component : list) {
if(component instanceof Composite){
System.out.println("xxxxxxxxxxxxxxCompositexxxxxxxxxxxxxx : "+component.name);
}else{
System.out.println("xxxxxxxxxxxxxxReafxxxxxxxxxxxxxx : "+component.name);
}
component.display();
}
}
}
/**
*
*/
package com.wangbiao.design.composite;
/**
* @Title: Client.java
* @Package com.wangbiao.design.composite
* @Description: TODO
* @author wangbiao
* @date 2014-9-28 上午10:04:16
* @version V1.0
*/
public class Client {
/**
* @param args
*/
public static void main(String[] args) {
Component component_one = new Composite("Compositexxxxxxxx");
component_one.add(new Reaf("reaf_one"));
component_one.add(new Reaf("reaf_two"));
Component component_two = new Composite("xxxxxxxxComposite");
component_two.add(new Reaf("reaf_three"));
component_two.add(new Reaf("reaf_four"));
component_one.add(component_two);
component_one.display();
}
/*
* result
xxxxxxxxxxxxxxReafxxxxxxxxxxxxxx : reaf_one
Reaf: reaf_one
xxxxxxxxxxxxxxReafxxxxxxxxxxxxxx : reaf_two
Reaf: reaf_two
xxxxxxxxxxxxxxCompositexxxxxxxxxxxxxx : xxxxxxxxComposite
xxxxxxxxxxxxxxReafxxxxxxxxxxxxxx : reaf_three
Reaf: reaf_three
xxxxxxxxxxxxxxReafxxxxxxxxxxxxxx : reaf_four
Reaf: reaf_four
*/
}