您的位置:首页 > 其它

组合模式的简单应用

2012-09-02 11:49 225 查看
public abstract class Component {
protected String name;
protected String type;

protected void setType(String type) {
this.type=type;
}
protected final String getType() {
return type;
}
protected void setName(String name) {
this.name=name;
}
protected final String getName() {
return name;
}
public abstract void print();
}

import java.util.ArrayList;
import java.util.Iterator;

public class Composite extends Component {
protected ArrayList<Component>list=new ArrayList<Component>();

public Composite() {

}
protected void add(Component c) {
this.list.add(c);
}
protected void remove(Component c) {
if(this.list.isEmpty()==false) this.list.remove(c);
}
protected void remove(int index) {
if(index <0 || index>=this.getSize()) {
System.out.println("out of bound!");
return;
}
else this.list.remove(index);
}
protected final Component getComponent(int index) {
if(index <0 || index>=this.getSize()) return null;
else return this.list.get(index);
}
protected final int getSize() {
return this.list.size();
}
@Override
public void print() {
// TODO Auto-generated method stub
System.out.println("I am: "+this.getType());
System.out.println("My name is: "+this.getName());
Iterator<Component>iterator=list.iterator();
while(iterator.hasNext()) {
iterator.next().print();
System.out.println("I belong to: "+this.getName());
}
}
}

public class Leaf extends Component {
public Leaf(String name) {
this.setName(name);
this.setType("leaf");
}
@Override
public void print() {
// TODO Auto-generated method stub
System.out.println("I am: "+this.getType());
System.out.println("My name : "+this.getName());
}

}

public class Branches extends Composite {
public Branches(String name) {
super();
this.setName(name);
this.setType("Branches");
}
public Branches() {

}
}

public class Tree extends Branches {

public Tree(String name) {
super();
// TODO Auto-generated constructor stub
this.setName(name);
this.setType("Tree");
}
}

public class Client {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Leaf leaf1=new Leaf("leaf1");
Leaf leaf2=new Leaf("leaf2");
Leaf leaf3=new Leaf("leaf3");
Leaf leaf4=new Leaf("leaf4");

Branches branches1=new Branches("branches1");
Branches branches2=new Branches("branches2");
branches1.add(leaf1);
branches1.add(leaf2);
branches2.add(leaf3);
branches2.add(leaf4);

Tree tree=new Tree("Binary Tree");
tree.add(branches1);
tree.add(branches2);
tree.print();
}
}


测试:

I am: Tree
My name is: Binary Tree
I am: Branches
My name is: branches1
I am: leaf
My name : leaf1
I belong to: branches1
I am: leaf
My name : leaf2
I belong to: branches1
I belong to: Binary Tree
I am: Branches
My name is: branches2
I am: leaf
My name : leaf3
I belong to: branches2
I am: leaf
My name : leaf4
I belong to: branches2
I belong to: Binary Tree


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息