码迷,mamicode.com
首页 > 编程语言 > 详细

c++ 结构型模式-组合(Composite)

时间:2020-01-24 00:31:06      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:对象   oid   rem   div   声明   getchild   col   cout   void   

1) 意图:

  将对象的组合成树型结构以表示“部分-整体”的层次结构。Composite使得用户对单个对象和整个对象的使用具有一直性

2) 结构:

 技术图片

 

 其中:

  1. Component 为组合中的对象声明接口
  2. Leaf表示“部分”的叶节点
  3. Composite 存储所有的节点,这样实现统一操作“整体”对象

 

3) 适用性:

  a. 想表示对象的部分-整体层次结构

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

4) 举例:

 

 1 #include <iostream>
 2 #include <list>
 3 class  Component
 4 {
 5 public:
 6     Component() {}
 7     virtual ~Component() {}
 8     virtual void  Operation() = 0;
 9     virtual void Add(Component*) {}
10     virtual void Remove(Component*) {}
11     virtual void GetChild(int) {}
12 };
13 class  Leaf1 : public Component
14 {
15 public:
16     virtual void  Operation()
17     {
18         std::cout << "print by Leaf1" << std::endl;
19     }
20 };
21 class  Leaf2 : public Component
22 {
23 public:
24     virtual void  Operation()
25     {
26         std::cout << "print by Leaf2" << std::endl;
27     }
28 };
29 class  Composite : public Component
30 {
31 public:
32     typedef std::list<Component*> ComList;
33     virtual void  Operation()
34     {
35         for (ComList::iterator it = m_comList.begin();
36             it != m_comList.end(); ++it)
37         {
38             (*it)->Operation();
39         }
40     }
41     virtual void Add(Component* p) 
42     {
43         m_comList.push_back(p);
44     }
45     virtual void Remove(Component*) 
46     {//
47     }
48     virtual void GetChild(int) 
49     {//
50     }
51 private:
52     ComList m_comList;
53 };
54 
55  int main()
56  {
57      Component* leaf1 = new Leaf1();
58      Component* leaf2 = new Leaf2();
59     
60      Component* composite = new Composite();
61      composite->Add(leaf1);
62      composite->Add(leaf2);
63      composite->Operation();
64 
65 
66 
67      delete composite;
68      delete leaf1;
69      delete leaf2;
70      system("pause");
71  }

 

c++ 结构型模式-组合(Composite)

标签:对象   oid   rem   div   声明   getchild   col   cout   void   

原文地址:https://www.cnblogs.com/ho966/p/12231593.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!