设计模式之组合模式
来源:互联网 发布:sim800c gprs接收数据 编辑:程序博客网 时间:2024/06/08 11:19
组合模式原理:将对象组合成树形结构以表示“部分-整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。组合模式包括的成员角色有:
树干(Component):组合中的对象声明接口,在适当情况下,实现所有类共有接口的默认行为。声明一个接口用于访问和管理Component的子部件。
树枝(Composite):定义有枝节点行为,用来存储子部件,在Component接口中实现与子部件有关的操作,比如增加删除。
叶子(Leaf):在组合中表示叶节点对象,叶节点没有子节点。
UML图如下:
代码如下:
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);
}
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);
}
@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 Display(int depth) {
String temp = "";
for (int i = 0; i < depth; i++)
temp += '-';
System.out.println(temp + name);
}
}
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 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);
}
@Override
public void Add(Component c) {
children.add(c);
}
@Override
public void Remove(Component c) {
children.remove(c);
}
@Override
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);
}
}
}
private List<Component> children = new ArrayList<Component>();
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 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);
}
}
}
0 0
- 设计模式之组合模式
- 设计模式之组合模式
- 设计模式之组合模式
- 设计模式之--组合模式
- 设计模式之组合模式
- 设计模式之组合模式
- 设计模式之组合模式
- 设计模式之组合模式
- 设计模式之---组合模式
- 设计模式之组合模式
- 设计模式之组合模式
- 设计模式之-------------组合模式
- 设计模式之组合模式
- 设计模式之组合模式
- 设计模式之组合模式
- 设计模式 之 组合模式
- 设计模式之组合模式
- 设计模式之组合模式
- C++基础总结(4)-----指针
- SecureCRT配色
- [LeetCode]217. Contains Duplicate
- Android混淆打包
- 笔记:Linux常用命令(四)压缩解压缩命令
- 设计模式之组合模式
- tiny6410快速开发环境配置指南
- Android WebView中那些不得不解决的坑~~
- 华为oj 字符串通配符
- 机器学习之路——回归诊断
- 1003 Emergency
- 搞清楚 Python traceback
- 算法设计---优先队列与索引优先队列
- javascript 原型链等疑难答案