设计模式之组合模式
来源:互联网 发布:广州银杉资本 知乎 编辑:程序博客网 时间:2024/05/16 01:48
组合模式
1. 组合模式:
将对象组合成树形结构以表示‘部分---整体’的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
2. 组合模式:
Component为组合中的对象声明接口,在适当情况下,实现所有类共有接口的默认行为。声明接口用于访问和管理Component的子部件。通常用Add和Remove方法提供增加或移除树叶或树枝的功能。
Leaf在组合中,表示叶节点对象,没有子节点。
Composite定义有枝节点行为,用来存储子部件,在Component接口实现与子部件有关的操作。比如增加和移除。
2. 组合模式解释:
为什么Leaf类中也有Add和Remove,树叶不是不可以再长分支吗?
有Add和Remove的叫透明方式,也即是说,在Component中声明所有用来管理子对象的办法,其中包括Add和Remove等。这样实现Component接口的所有子类都具备了Add和Remove。这样做的好处就是叶节点和枝节点对外界没有区别,它们具备完全一致的接口,因为Leaf类本身不具备Add和Remove方法,所以实现也没有意义。
安全方式:也就是在Component接口中不去声明Add和Remove方法,那么子类的Leaf也就不需要去实现它,而是在Composite声明所有用来管理子类对象的方法,不过由于不透明,所以树叶和树枝不具有相同接口,客户端需要做相应判断,带来了不便。
什么地方用组合模式呢?
当发现需求中体现部分与整体层次的结构时,以及你希望用户可以忽略组合对象与单个对象的不同,统一的使用组合结构中的所有对象时,就应该考虑。
4. 组合模式的例子:
例子1:
就如文档里的文字,对单个字的处理和对多个字、甚至整个文档的处理,其实是一样的,用户希望一直对待,程序开发者也希望一致处理。
#include <iostream>#include <vector>#include <string>using namespace std;class Component{public:string name;Component(string name){this->name=name;}virtual void add(Component *)=0;virtual void remove(Component *)=0;virtual void display(int)=0;};class Leaf:public Component{public:Leaf(string name):Component(name){}void add(Component *c){cout<<"leaf cannot add"<<endl;}void remove(Component *c){cout<<"leaf cannot remove"<<endl;}void display(int depth){string str(depth,'-');str+=name;cout<<str<<endl;}};class Composite:public Component{private:vector<Component*> component;public:Composite(string name):Component(name){}void add(Component *c){component.push_back(c);}void remove(Component *c){vector<Component*>::iterator iter=component.begin();while(iter!=component.end()){if(*iter==c){component.erase(iter);}iter++;}}void display(int depth){string str(depth,'-');str+=name;cout<<str<<endl;vector<Component*>::iterator iter=component.begin();while(iter!=component.end()){(*iter)->display(depth+2);iter++;}}};int main(){Component *p=new Composite("小李"); p->add(new Leaf("小王"));p->add(new Leaf("小强"));Component *sub=new Composite("小虎"); sub->add(new Leaf("小王"));sub->add(new Leaf("小明"));sub->add(new Leaf("小柳"));p->add(sub);p->display(0);cout<<"*******"<<endl;sub->display(2);return 0;}
- 设计模式之组合模式
- 设计模式之组合模式
- 设计模式之组合模式
- 设计模式之--组合模式
- 设计模式之组合模式
- 设计模式之组合模式
- 设计模式之组合模式
- 设计模式之组合模式
- 设计模式之---组合模式
- 设计模式之组合模式
- 设计模式之组合模式
- 设计模式之-------------组合模式
- 设计模式之组合模式
- 设计模式之组合模式
- 设计模式之组合模式
- 设计模式 之 组合模式
- 设计模式之组合模式
- 设计模式之组合模式
- js正则表达式:只能输入1到125之间任意数字
- 会场安排问题
- Batch Normalization 的原理解读
- jQuery实现拖动
- MM--如何控制采购申请转变为采购订单数量不超过采购申请数量
- 设计模式之组合模式
- myeclipse报错:The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path
- Git命令行选项
- java编程:用类描述计算机中CPU的速度和硬盘的容量
- fragment实例----底部导航栏
- Java中打印输出到文件
- 【基础中心】笔记一--Spring Boot
- QT中将多个UI文件对应的类放在一个头文件和源文件中
- 括号匹配问题