设计模式-Decorator(结构型模式) 用于通过 组合 的方式 给定义的类 添加新的操作,这里不用 继承 的原因是 增加了系统的复杂性,继承使深度加深。

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

//Decorator.h

#pragma once

class Component
{
public:
    virtual ~Component();
    virtual void Operation();
protected:
    Component();
};

class ConcreateComponent :public Component
{
public:
    virtual ~ConcreateComponent();
    ConcreateComponent();
    void Operation();
};

class Decorator :public Component
{
public:
    Decorator(Component* com);
    virtual ~Decorator();
    void Operation();
protected:
    Component* _com;
private:
};

class ConcreateDecorator :public Decorator
{
public:
    ConcreateDecorator(Component* com);
    virtual ~ConcreateDecorator();
    void Operation();
    void addBehavor();
protected:
private:
};

//Decorator.cpp

#include"Decorator.h"
#include<iostream>

Component::Component(){}
Component::~Component(){}
void Component::Operation(){}

ConcreateComponent::ConcreateComponent(){}
ConcreateComponent::~ConcreateComponent(){}
void ConcreateComponent::Operation()
{
    std::cout << "Concreate Component Operation..." << std::endl;
}

Decorator::Decorator(Component* com)
{
    this->_com = com;
}
Decorator::~Decorator()
{
    delete _com;
}
void Decorator::Operation(){}

ConcreateDecorator::ConcreateDecorator(Component* com):Decorator(com){}
ConcreateDecorator::~ConcreateDecorator(){}
void ConcreateDecorator::addBehavor()
{
    std::cout << "CreateDecorator::AddedBehavior.." << std::endl;
}
void ConcreateDecorator::Operation()
{
    _com->Operation();
    this->addBehavor();
}

//main.cpp

#include"Decorator.h"
#include<iostream>
#include<string>

int main(int args, char*argv)
{
    Component* com = new ConcreateComponent();
    Decorator*dec = new ConcreateDecorator(com);
    dec->Operation();
    delete dec;
    getchar();
    return 0;
}
posted @ 2019-12-21 16:33  fourmii  阅读(200)  评论(0编辑  收藏  举报