• 设计模式学习之----组合模式


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

      例如:文件和目录的显示,单个对象是文件,组合对象是目录,一致性是显示。

     1 #include <iostream>
     2 #include <string>
     3 #include <list>
     4 
     5 using namespace std;
     6 class IFile
     7 {
     8 public:
     9     virtual void display() = 0;
    10     virtual int add(IFile *iFile) = 0;
    11     virtual int remove(IFile *iFile) = 0;
    12     virtual list<IFile*>* getChild() = 0;
    13 };
    14 
    15 //文件节点
    16 class File : public IFile
    17 {
    18 public:
    19     File(string name)
    20     {
    21         m_name = name;
    22     }
    23     virtual void display()
    24     {
    25         cout << m_name << endl;
    26     }
    27 
    28     virtual int add(IFile *iFile)
    29     {
    30         return -1;
    31     }
    32     virtual int remove(IFile *iFile)
    33     {
    34         return -1;
    35     }
    36     virtual list<IFile*>* getChild()
    37     {
    38         return NULL;
    39     }
    40 
    41 private:
    42     string m_name;
    43 };
    44 
    45 //目录节点
    46 class Dir : public IFile
    47 {
    48 public:
    49     Dir(string name)
    50     {
    51         m_name = name;
    52         m_list = new list<IFile *>;
    53     }
    54 
    55     virtual void display()
    56     {
    57         cout << m_name << endl;
    58     }
    59 
    60     virtual int add(IFile *iFile)
    61     {
    62         m_list->push_back(iFile);
    63         return 1;
    64     }
    65 
    66     virtual int remove(IFile *iFile)
    67     {
    68         m_list->remove(iFile);
    69         return 1;
    70     }
    71 
    72     virtual list<IFile*>* getChild()
    73     {
    74         return m_list;
    75     }
    76 
    77 private:
    78     string m_name;
    79     list<IFile*> *m_list;
    80 };
    81 
    82 int main()
    83 {
    84     Dir *root = new Dir("C.....");
    85     root->display();
    86     Dir *dir1   = new Dir("1111dir1");
    87     File *file1 = new File("file1");
    88     root->add(dir1);
    89     root->add(file1);
    90 
    91     using iter = list<IFile*>::iterator;
    92     list<IFile*> *list = root->getChild();
    93     for (iter it = list->begin(); it != list->end(); it++)
    94     {
    95         (*it)->display();
    96     }
    97 
    98     return system("pause");
    99 }
  • 相关阅读:
    js 跨域问题 汇总
    js 数组的常用方法
    移动端web总结
    BitCoinCore配置文件解读
    同一台主机部署两个比特币钱包以及rpc服务的摘要
    ubuntu启动进程笔记
    C#按制定的环境编译替换不出对应的配置项的解决措施。
    【转】Javascript中使用WScript.Shell对象执行.bat文件和cmd命令
    C#执行javascript代码,执行复杂的javascript代码新方式
    linux小笔记
  • 原文地址:https://www.cnblogs.com/henkk/p/12937277.html
Copyright © 2020-2023  润新知