Riordon

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: :: :: 管理 ::

引言:当希望忽略单个对象和组合对象的区别,统一使用组合结构中的所有对象(将这种“统一”性封装起来)

Composite(组合模式):将对象组合成树形结构以表示“部分-整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。

实例:

View Code
 1 #include <iostream>
 2 using namespace std;
 3 #include <list>
 4 
 5 class CComponent
 6 {
 7 public:
 8     virtual void Operation() = 0;
 9     virtual void Add(CComponent *pChild) = 0;
10     virtual void Remove(CComponent *pChild) = 0;
11     virtual CComponent* GetChild(int i)=0;
12 };
13 
14 class CLeaf :public CComponent
15 {
16 public:
17     virtual void Operation()
18     {
19         cout<<"基本对象";
20     }
21     virtual void Add(CComponent *pChild)
22     {
23     }
24 
25     virtual void Remove(CComponent *pChild)
26     {
27     }
28 
29     virtual CComponent* GetChild(int i)
30     {
31         return NULL;
32     }
33 };
34 
35 class CComposite: public CComponent
36 {
37 public:
38     virtual void Operation()
39     {
40         cout<<"组合对象(";
41         for(list<CComponent*>::iterator it = m_Children.begin(); it != m_Children.end(); ++it)
42         {
43             (*it)->Operation();
44             cout<<" ";
45         }
46         cout<<")";
47     }
48 
49     virtual void Add(CComponent *pChild)
50     {
51         m_Children.push_back(pChild);
52     }
53 
54     virtual void Remove(CComponent *pChild)
55     {
56         m_Children.remove(pChild);
57     }
58 
59     virtual CComponent* GetChild(int i)
60     {
61         list<CComponent*>::iterator it;
62         for(it = m_Children.begin(); it != m_Children.end() && (i > 0); ++it,--i);
63         return *it;
64     }
65 
66     virtual ~CComposite()
67     {
68         for(list<CComponent*>::iterator it = m_Children.begin(); it != m_Children.end(); ++it)
69         {
70             delete *it;
71         }
72     }
73 
74 private:
75     list<CComponent*> m_Children;
76 };
77 
78 int main(int argc, char* argv[])
79  {
80      CComponent *pChild1 = new CComposite();
81     pChild1->Add(new CLeaf());
82     pChild1->Add(new CLeaf());
83 
84     CComponent *pChild2 = new CComposite();
85     pChild2->Add(new CLeaf());
86     pChild1->Add(pChild2);
87     pChild1->Operation();
88 
89     delete pChild1;
90 
91     cout<<endl;
92 
93     return 0;
94 }

小结:

 当想表达对象的部分-整体的层次结构时

 希望用户忽略组合对象与单个对象的不同,用户将统一地使用组合结构中的所有对象时

posted on 2013-05-09 22:32  Riordon  阅读(217)  评论(0)    收藏  举报