组合模式PPT

Download Report

Transcript 组合模式PPT

JAVA设计模式——组合模式
小组成员:
陈冬儿 牛钰茜 王泽民
王佳镭 帅治林 温 赟
目录
1. 什么是组合模式
2. 组合模式应用情境
3. 组合模式使用实例
4. 组合模式的使用讨论
什么是组合模式

定义:

将对象组合成树形结构以表示‘部分-整体’的层次结构。组合模式
使得用户对单个对象和组合对象的使用具有一致性。
1.
2.
3.
4.
树形结构
部分—整体
层次结构
单个对象与组合对象
组合模式使用情境

1. 想要表示对象的部分—整体关系

2. 想要忽略组合对象与单个对象的差异
组合模式使用实例

结构:
枝节点:组合对象,存储子部件
叶节点:单个对象,没有子部件
接口:对象声明接口,访问和管理子部件
代码示例

接口(Component)
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);
}
代码示例

叶节点(Leaf)
class Leaf extends Component {
public Leaf(String name) {
super(name);
}
public void Add(Component c) {
System.out.println("Can not add to a leaf");
}
public void Remove(Component c) {
System.out.println("Can not remove from a leaf");
}
public void Display(int depth) {
String temp = "";
for (int i = 0; i < depth; i++)
temp += '-';
System.out.println(temp + name);
}
}
代码示例

枝节点(Composite)
class Composite extends Component {
private List<Component> children = new ArrayList<Component>();
public Composite(String name) {
super(name);
}
public void Add(Component c) {
children.add(c);
}
public void Remove(Component c) {
children.remove(c);
}
public void Display(int depth) {
String temp = "";
for (int i = 0; i < depth; i++)
temp += '-';
System.out.println(temp + name);
for (Component c : children) {
c.Display(depth + 2);
}
}
}
代码示例

用户(Client)
public class CompositePattern {
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.Display(1);
}
}
使用讨论——透明性

使用方式
在Component里面声明所有的用来管理子类对象的方法,以达到Component接口的最大化
优点:树叶与分支没有区别
缺点:树叶不存在子类,某些方法对
叶节点不适用
使用讨论——安全性

使用方式
只在Composite里面声明所有的用来管理子类对象的方法
优点:叶节点没有无用的方法
缺点:失去了透明性
使用讨论——总结

相对于安全性,我们比较强调透明性。对于第一种方式中叶子节
点内不需要的方法可以使用空处理或者异常报告的方式来解决。
public void Add(Component c) {
System.out.println("Can not add to a leaf");
}
public void Remove(Component c) {
System.out.println("Can not remove from a leaf");
}
题目
利用组合模式,模拟东南大学
的组织结构,下面是类图: