设为首页 加入收藏

TOP

composite pattern -- 组合模式
2013-01-01 14:40:37 来源: 作者: 【 】 浏览:221
Tags:composite pattern 组合 模式
composite pattern称为组合模式

在面向对象的系统中,我们经常会遇到一类具有"容器"特征的对象,即它们在充当对象的同时,又是其他对象的容器。

“Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.” – GoF

 

举例:

 

在我们常用的windows操作系统中,"文件"的概念大家都知道,不仅可以是文件夹又可以是普通文件。文件夹下面又可放文件夹以及文件,通俗理解是一个树模型。Composite设计模式就是将客户代码与复杂的对象容器结构解耦,让对象容器自己来实现自身的复杂结构,从而使得客户代码就像处理简单对象(文件)一样来处理复杂的对象容器(目录)

实例解析(完成一个树形结构)
有一个文件夹(work)下面有两个文件夹(Daily Record,Key Document)以及2个文件(Address Book,Schedule)。Daily Record下有两个文件(2012-12-18,2012-12-19),Key Document下有一个文件(Meeting document)。
  1class File  2{  3public:  4         File(std::string n)  5        :name(n)  6        {}  7virtual ~File( ){}  8virtualvoid Add(File *s){}  9virtualint Remove(int n){} 10virtual File* getChild(int n){}; 11virtualvoid Operation( )=0; 12protected: 13         std::string name; 14}; 15 16class Leaf:public File 17{ 18public: 19         Leaf(std::string n) 20        :File(n) 21        { } 22void Operation( ); 23}; 24void Leaf::Operation( ) 25{ 26     std::cout<<"The leaf is "<<name<<std::endl; 27} 28 29class subFile:public File 30{ 31public: 32         subFile(std::string n) 33        :name(n) 34        {} 35         ~subFile( ); 36void Add(File *s); 37int Remove(int n); 38         File * getChild(int n); 39void  Operation( ); 40private: 41         std::vector<File*> listFile; 42}; 43 subFile::~subFile( ) 44{ 45} 46void subFile::Add(File *s) 47{ 48     listFile.push_back(s);    49} 50int subFile::Remove(int n) 51{ 52if(n>listFile.size( )||n<0) 53return -1; 54     listFile.erase(listFile.begin( )+n); 55return1; 56} 57 File* subFile::getChild(int n) 58{ 59if(n>listFile.size( )||n<0) 60return NULL; 61return listFile[n]; 62} 63void subFile::Operation( ) 64{ 65     std::vector<File*>::iterator iter=listFile.begin( ); 66while( iter!=listFile.end( ) ) 67    { 68//否则编译器会报错 69         std::cout<<"This document is "<<name<<std::endl; 70         (*iter)->  Operation( ); 71         iter++; 72    } 73} 74 75int main(int argc,char **argv) 76{ 77     File* f1=new subFile("Work"); 78     File* f2=new subFile("Daily Recond"); 79     File* f3=new subFile("Key Document); 80     File* f4=new Leaf("Address Book"); 81     File* f5=new Leaf("Schedule"); 82     f1->Add(f2); 83     f1->Add(f3); 84     f1->Add(f4); 85     f1->Add(f5); 86     File* f6=new Leaf("2012-12-18"); 87     File* f7=new Leaf("2012-12-19"); 88     f2->Add(f6); 89     f2->Add(f7); 90     File* f8=new Leaf("Meeting Document"); 91     f3->Add(f8); 92     f1->Operation( ); 93    delete f1; 94    delete f2; 95    delete f3; 96    delete f4; 97    delete f5; 98    delete f6; 99    delete f7;100    delete f8;101return0;102 }

 

运行结果为

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇decorator pattern -- 装饰模式 下一篇bridge pattern -- 桥接模式

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: