您的位置:首页 > 其它

设计模式之组合模式(Composite)

2016-08-04 14:49 369 查看

概述

是一种结构型模式,将对象以树形结构组织起来,以表示“部分 - 整体”的层次结构,使得客户端对单个对象和组合对象的使用具有唯一性。

UML类图



上面的类图包含的角色:

Component:为参加组合的对象声明一个公共的接口,不管是组合还是叶节点。

Leaf:在组合中表示叶子结点对象,叶子结点没有子结点。

Composite:表示参加组合的有子对象的对象,并给出树枝构建的行为;

代码示例

import java.util.ArrayList;
import java.util.List;

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 GetChild(int depth);
}

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 GetChild(int depth) {
String temp = " ";
for (int i = 0; i < depth; i++) {
temp += "-";
System.out.println(temp + name);
}
}

}

class Composite extends Component {

private List<Component> children = new ArrayList<>();

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 GetChild(int depth) {

for (Component c : children) {
c.GetChild(depth);
}
}

}

public class Main {

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

Composite compX = new Composite("Composite X");
compX.Add(new Leaf("Leaf XA"));
compX.Add(new Leaf("Leaf XB"));
root.Add(compX);

Composite compXY = new Composite("Composite XY");
compXY.Add(new Leaf("Leaf XYA"));
compXY.Add(new Leaf("Leaf XYB"));
compX.Add(compXY);

root.GetChild(3);
}

}


应用场景

1.要求表示对象的部分-整体层次结构。

2.想要客户端忽略组合对象与单个对象的差异,客户端将统一地使用组合结构中的所有对象。

组合模式定义由Leaf对象和Composite对象组成的类结构;

使得客户端变得简单;

它使得添加或删除子部件变得很容易。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  设计模式