zoukankan      html  css  js  c++  java
  • 设计模式-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;
    }
  • 相关阅读:
    进程
    并发编程小结
    操作系统发展史
    基于socketsever实现并发的socket编程
    UDP套接字
    粘包问题及解决
    socket套接字编程
    TCP协议与三次握手四次挥手
    OSI七层协议
    互联网的组成
  • 原文地址:https://www.cnblogs.com/fourmi/p/12077657.html
Copyright © 2011-2022 走看看