设计模式-Composite(创建型模式) 用于 递归构建 树 状 的组合结构,与Decorator的区别是 Composite旨在通过构造子类而添加新操作,而Decorator直接添加新操作。

以下代码来源: 设计模式精解-GoF 23种设计模式解析附C++实现源码

//Component.h

#pragma once

class Component
{
public:
    Component();
    virtual ~Component();
    virtual void Operation() = 0;
    virtual void Add(const Component&);
    virtual void Remove(const Component&);
    virtual Component* getChild(int);
protected:
private:

};

//Component.cpp

#include"Component.h"
Component::Component(){}
Component::~Component(){}
void Component::Add(const Component& com){}
void Component::Remove(const Component& com){}
Component* Component::getChild(int index)
{
    return 0;
}

//composite.h

#include"Component.h"
#include<vector>

class Composite :public Component
{
public:
    Composite();
    virtual ~Composite();
    void Add(Component* com); 
    void Remove(Component* com);
    void Operation();
    Component* Getchild(int index);
protected:
private:
    std::vector<Component*>comVec;
};

//Composite.cpp

#include"Component.h"
#include"composite.h"

const int null = 0;

Composite::Composite(){}
Composite::~Composite(){}

void Composite::Operation(){
    for (std::vector<Component*>::iterator comIter = comVec.begin(); comIter != comVec.end(); ++comIter)
    {
        (*comIter)->Operation();
    }
}
void Composite::Add(Component* com)
{
    comVec.push_back(com);
}
void Composite::Remove(Component* com)
{
    //comVec.erase(&com);//此处有问题,求解释!!!
}
Component* Composite::Getchild(int index)
{
    return comVec[index];
}

//Leaf.h

#include"Component.h"
class Leaf :public Component
{
public:
    Leaf();
    virtual ~Leaf();
    void Operation();
protected:
private:

};

//Leaf.cpp

#include"Leaf.h"
#include<iostream>
Leaf::Leaf(){
}
Leaf::~Leaf(){}
void Leaf::Operation(){
    std::cout << "Leaf Operation..." << std::endl;
}

//main.cpp

#include"Component.h"
#include"composite.h"
#include"Leaf.h"
#include<iostream>
#include<string>
int main(int args, char* argv)
{
    Leaf* I = new Leaf();
    I->Operation();
    Composite* com = new Composite();
    com->Add(I);
    com->Operation();
    Component* II = com->Getchild(0);
    getchar();
    return 0;
}
上一篇:LeetCode-129-Sum Root to Leaf Numbers


下一篇:[Swift Weekly Contest 122]LeetCode988. 从叶结点开始的最小字符串 | Smallest String Starting From Leaf