设计模式:可复用面向对象软件及基础:3-3 结构型模式:组合模式(composite)
发布日期:2021-05-06 15:37:04 浏览次数:23 分类:精选文章

本文共 2323 字,大约阅读时间需要 7 分钟。

组合模式

概念

    Composite模式也叫组合模式,是构造型的设计模式之一。通过递归手段来构造树形的对象结构,并可以通过一个对象来访问整个对象树。

角色和职责

 

Component (树形结构的节点抽象)

- 为所有的对象定义统一的接口(公共属性,行为等的定义)

- 提供管理子节点对象的接口方法

- [可选]提供管理父节点对象的接口方法

 

Leaf (树形结构的叶节点)

Component的实现子类

 

Composite(树形结构的枝节点)

-Component的实现子类

适用于:

单个对象和组合对象的使用具有一致性。将对象组合成树形结构以表示“部分--整体”

案例

#include 
using namespace std;#include "list"#include "string"//class IFile{public: virtual void display() = 0; virtual int add(IFile *ifile) = 0; virtual int remove(IFile *ifile) = 0; virtual list
* getChild() = 0;protected:private:};class File : public IFile{public: File(string name) { m_list = NULL; m_name = ""; m_name = name; } ~File() { if (m_list != NULL) { delete m_list; } } virtual void display() { cout << m_name << endl; } virtual int add(IFile *ifile) { return -1; } virtual int remove(IFile *ifile) { return -1; } virtual list
* getChild() { return NULL; }private: list
* m_list; string m_name;};class Folder : public IFile{public: Folder(string name) { m_name = name; m_list = new list
; } ~Folder() { if (m_list == NULL) { delete m_list; } } virtual void display() { cout << m_name << endl; } virtual int add(IFile *ifile) { m_list->push_back(ifile); return 0; } virtual int remove(IFile *ifile) { m_list->remove(ifile); return 0; } virtual list
* getChild() { return m_list; }private: list
* m_list; string m_name;};void showTree(IFile *ifile, int level){ list
*l = NULL; int i = 0; for (i=0; i
display(); l = ifile->getChild(); if (l != NULL) { for (list
::iterator it=l->begin(); it!=l->end(); it++) { if ( (*it)->getChild() == NULL) { for (i=0; i<=level; i++) //注意 <= { printf("\t"); } (*it)->display(); } else { showTree((*it), level + 1); } } }}void main(){ Folder *root = new Folder("C:"); Folder *dir1 = new Folder("111dir"); File *txt1 = new File("aaa.txt"); Folder *dir12 = new Folder("222dir"); //dir12->display(); File *txt12 = new File("222.txt"); //txt12->display(); root->display(); root->add(dir1); root->add(txt1); dir1->add(dir12); dir1->add(txt12); /* list
*l = dir1->getChild(); for (list
::iterator it=l->begin(); it!=l->end(); it++) { (*it)->display(); } */ //开发一个递归函数 现在根结点下的所有子结点 cout << "测试递归函数" << endl; showTree(root, 0); delete txt12; delete dir12; delete dir1; delete txt1; delete root; cout<<"hello..."<

 

上一篇:设计模式:可复用面向对象软件及基础:3-4 结构型模式:装饰模式(decorator)
下一篇:设计模式:可复用面向对象软件及基础:3-2 结构型模式:桥接模式(Bridge)

发表评论

最新留言

关注你微信了!
[***.104.42.241]2025年03月22日 15时54分12秒