您的位置:首页 > 编程语言 > Java开发

十六、组合模式 Composite

2017-03-29 17:24 369 查看

一、定义

组合模式:将对象组合成树形结构以表示‘部分-整体’的层次结构。组合模式使得用户对单个对象个组合对象的使用具有一致性。

应用:当你发现需求中是体现部分与真题层次的结构是,以及你希望用户可以忽略组合对象与单个对象的不同,统一使用组合结构中的所有对象时,就应该考虑使用组件设计模式。

二、结构图



三、代码示例

/**
* @use 测试组合模式
* @author lattice
* @date 2017-01-03
*/
public class CompositeTest {

public static void main(String[] args) {
Composite root=new Composite("root");
root.add(new Leaf("leaf A"));

Composite comp=new Composite("composite A");
comp.add(new Leaf("leaf A of composite A"));
comp.add(new Leaf("leaf B of composite A"));

root.add(comp);

root.add(new Leaf("leaf B"));
root.display(1);

/**
* 输出结果
*
-root
---leaf A
---composite A
-----leaf A of composite A
-----leaf B of composite A
---leaf B

*/
}
}

abstract class Component {
protected String name;

public Component(String name) {
this.name = name;
}

public String getString(String str, int number) {
String result = "";
for (int i = 0; i < number; i++) {
result += str;
}
return result;
}

public abstract void add(Component c);

public abstract void remove(Component c);

public abstract void display(int depth);
}

class Leaf extends Component {
public Leaf(String name) {
super(name);
}

public void add(Component c) {
System.out.println("connot add to a leaf");
}

public void remove(Component c) {
System.out.println("connot remove from a leaf");
}

public void display(int depth) {
System.out.println(getString("-", depth) + name);
}
}

class Composite extends Component {
private ArrayList<Component> childrens = new ArrayList<Component>();
public Composite(String name) {
super(name);
}

public void add(Component c) {
childrens.add(c);
}

public void remove(Component c) {
childrens.remove(c);
}

public void display(int depth) {
System.out.println(getString("-", depth) + name);
for(Component sb:childrens){
sb.display(depth+2);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息