zoukankan      html  css  js  c++  java
  • C++的组合(Composite)模式

    现欲构造一个文件/目录树,采用组合(Composite)设计模式来设计,得到的类图如下:

    C++代码为:

    1 #include <list>
    2 #include <iostream>
    3 #include <string>
    4
    5  using namespace std;
    6
    7  class AbstractFile {
    8 protected:
    9 string name; /*文件或目录名*/
    10 public:
    11 void printName() {cout<<name<<endl;} /*打印文件或目录名称*/
    12 virtual void addChild(AbstractFile *file)=0; /*给一个目录增加子目录或文件*/
    13 virtual void removeChild(AbstractFile *file)=0; /*删除一个目录的子目录或文件*/
    14 virtual list<AbstractFile *> *getChildren()=0; /*保存一个目录的子目录或文件*/
    15 };
    16
    17 class File:public AbstractFile{
    18 public:
    19 File(string name) {this->name=name;}
    20 void addChild(AbstractFile *file) {return;}
    21 void removeChild(AbstractFile *file) {return;}
    22 list<AbstractFile *> *getChildren() {return NULL;}
    23 };
    24
    25 class Folder:public AbstractFile {
    26 private:
    27 list<AbstractFile *> childList; /*存储子目录或文件*/
    28 public:
    29 Folder(string name) {this->name=name;}
    30 void addChild(AbstractFile *file) {childList.push_back(file);}
    31 void removeChild(AbstractFile *file) {childList.remove(file);}
    32 list<AbstractFile *> *getChildren() {return &childList;}
    33 };
    34
    35 int main() {
    36 AbstractFile *rootFolder=new Folder("c:\\");
    37 AbstractFile *compositeFolder=new Folder("composite");
    38 AbstractFile *WindowsFolder=new Folder("Windows");
    39 AbstractFile *file=new File("TestComposite.C++");
    40 rootFolder->addChild(compositeFolder);
    41 rootFolder->addChild(WindowsFolder);
    42 compositeFolder->addChild(file);
    43 rootFolder->printName();
    44 compositeFolder->printName();
    45 WindowsFolder->printName();
    46 file->printName();
    47 return 0;
    48 }
  • 相关阅读:
    事务
    触发器
    入行大数据必须知道的事!
    5G如何使云计算更加前卫
    2021年加密货币和区块链风向
    2020年数据存储管理发生的7种变化
    如何克服物联网中数据集成的挑战
    从开发到产出:关于机器学习的七则干货建议
    如何利用机器学习进行静态分析
    AI如何改变DevOps?
  • 原文地址:https://www.cnblogs.com/djcsch2001/p/2049239.html
Copyright © 2011-2022 走看看