设计模式-1.8组合模式

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

 1 class Company  
 2 {
 3 public:
 4     Company(string name) { m_name = name; }
 5     virtual ~Company(){}
 6     virtual void Add(Company *pCom){}
 7     virtual void Show(int depth) {}
 8 protected:
 9     string m_name;
10 };
11 //具体公司
12 class ConcreteCompany : public Company  
13 {
14 public:
15     ConcreteCompany(string name): Company(name) {}
16     virtual ~ConcreteCompany() {}
17     void Add(Company *pCom) { m_listCompany.push_back(pCom); } //位于树的中间,可以增加子树
18     void Show(int depth)
19     {
20         for(int i = 0;i < depth; i++)
21             cout<<"-";
22         cout<<m_name<<endl;
23         list<Company *>::iterator iter=m_listCompany.begin();
24         for(; iter != m_listCompany.end(); iter++) //显示下层结点
25             (*iter)->Show(depth + 2);
26     }
27 private:
28     list<Company *> m_listCompany;
29 };
30 //具体的部门,财务部
31 class FinanceDepartment : public Company 
32 {
33 public:
34     FinanceDepartment(string name):Company(name){}
35     virtual ~FinanceDepartment() {}
36     virtual void Show(int depth) //只需显示,无限添加函数,因为已是叶结点
37     {
38         for(int i = 0; i < depth; i++)
39             cout<<"-";
40         cout<<m_name<<endl;
41     }
42 };
43 //具体的部门,人力资源部
44 class HRDepartment :public Company  
45 {
46 public:
47     HRDepartment(string name):Company(name){}
48     virtual ~HRDepartment() {}
49     virtual void Show(int depth) //只需显示,无限添加函数,因为已是叶结点
50     {
51         for(int i = 0; i < depth; i++)
52             cout<<"-";
53         cout<<m_name<<endl;
54     }
55 };

 

 1 int main()
 2 {
 3     Company *root = new ConcreteCompany("总公司");
 4     Company *leaf1=new FinanceDepartment("财务部");
 5     Company *leaf2=new HRDepartment("人力资源部");
 6     root->Add(leaf1);
 7     root->Add(leaf2);
 8 
 9     //分公司A
10     Company *mid1 = new ConcreteCompany("分公司A");
11     Company *leaf3=new FinanceDepartment("财务部");
12     Company *leaf4=new HRDepartment("人力资源部");
13     mid1->Add(leaf3);
14     mid1->Add(leaf4);
15     root->Add(mid1);
16     //分公司B
17     Company *mid2=new ConcreteCompany("分公司B");
18     FinanceDepartment *leaf5=new FinanceDepartment("财务部");
19     HRDepartment *leaf6=new HRDepartment("人力资源部");
20     mid2->Add(leaf5);
21     mid2->Add(leaf6);
22     root->Add(mid2);
23     root->Show(0);
24 
25     delete leaf1; delete leaf2;
26     delete leaf3; delete leaf4;
27     delete leaf5; delete leaf6;    
28     delete mid1; delete mid2;
29     delete root;
30     return 0;
31 }

  上面的实现方式有缺点,就是内存的释放不好,需要客户自己动手,非常不方便。有待改进,比较好的做法是让ConcreteCompany类来释放。因为所有的指针都是存在ConcreteCompany类的链表中。C++的麻烦,没有垃圾回收机制。

posted @ 2014-10-07 11:48  SoftWare And Hardware  阅读(163)  评论(0编辑  收藏  举报