设计模式-装饰模式

适用情境:给一个类添加一些额外的功能,而不修改原来类的代码.添加的功能一般不是非常重要的核心功能,而是较少使用的次要功能.添加的功能放在一个单独的类中,客户端可以对添加的功能进行选择.

优点:新添加的功能不影响被装饰类的功能,不增加被装饰类的复杂度.
缺点:需要修改客户端代码.

// component.h
#ifndef COMPONENT_H
#define COMPONENT_H

class Component
{
public:
    Component();
    virtual void Operation() = 0;
};

#endif // COMPONENT_H
// component.cpp
#include "component.h"

Component::Component()
{
}
// concretecomponent.h
#ifndef CONCRETECOMPONENT_H
#define CONCRETECOMPONENT_H

#include "component.h"

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

#endif // CONCRETECOMPONENT_H
// concretecomponent.cpp
#include <iostream>
#include "concretecomponent.h"

ConcreteComponent::ConcreteComponent()
{}

void ConcreteComponent::Operation()
{
    std::cout << "ConcreteCompoent::operation()" << std::endl;
}
// decorator.h
#ifndef DECORATOR_H
#define DECORATOR_H

#include "component.h"

class Decorator : public Component
{
public:
    Decorator(Component *tmp);
    virtual void Operation();
public:
    Component *m_component;
};

#endif // DECORATOR_H
// decorator.cpp
#include "decorator.h"

Decorator::Decorator(Component *tmp)
{
    m_component = tmp;
}

void Decorator::Operation()
{
    m_component->Operation();
}
// concretedecorator.h
#ifndef CONCRETEDECORATOR_H
#define CONCRETEDECORATOR_H

#include "decorator.h"

class ConcreteDecorator : public Decorator
{
public:
    ConcreteDecorator(Component *tmp);
    virtual void Operation();
    virtual void NewOperation();
};

#endif // CONCRETEDECORATOR_H
// concretedecorator.cpp
#include <iostream>
#include "concretedecorator.h"

ConcreteDecorator::ConcreteDecorator(Component *tmp) : Decorator(tmp)
{

}

void ConcreteDecorator::Operation()
{
    m_component->Operation();
    NewOperation();
}

void ConcreteDecorator::NewOperation()
{
     std::cout << "ConcreteDecorator::NewOperation()" << std::endl;
}

客户端:

// main.cpp
#include <iostream>

#include "component.h"
#include "decorator.h"
#include "concretedecorator.h"
#include "concretecomponent.h"

using namespace std;

int main(int argc, char *argv[])
{
    Component *component = new ConcreteComponent();
    Component *component1 = new ConcreteDecorator(component);
    component1->Operation();

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值