先上uml图:
意图:动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。
uml解析:装饰者模式又名包装器,顾名思义就是给某个对象添加一些功能,而不是给整个类添加一些功能。Component跟Decorator是聚合关系,子类ConcreteDecoratorA和ConcreteDecoratorB实现具体对Component的修饰。
下面给出可执行的示例代码:
Decorator.h
#pragma once
#include <iostream>
using namespace std;
class Component
{
public:
Component(void);
virtual ~Component(void);
virtual void Operation()=0;
};
class ConcreteComponent:public Component
{
public:
void Operation();
};
class Decorator:public Component
{
public:
Decorator(Component *component):m_Component(component){}
void Operation();
protected:
Component *m_Component;
};
class ConcreteDecoratorA:public Decorator
{
public:
ConcreteDecoratorA(Component *component):Decorator(component){}
void Operation();
void AddState();
};
class ConcreteDecoratorB:public Decorator
{
public:
ConcreteDecoratorB(Component *component):Decorator(component){}
void Operation();
void AddBehavior();
};
Decorator.cpp
#include "Component.h"
Component::Component(void)
{
}
Component::~Component(void)
{
}
void ConcreteComponent::Operation()
{
cout<<"ConcreteComponent"<<endl;
}
void Decorator::Operation()
{
m_Component->Operation();
};
void ConcreteDecoratorA::AddState()
{
cout<<"AddState"<<endl;
}
void ConcreteDecoratorA::Operation()
{
AddState();
m_Component->Operation();
}
void ConcreteDecoratorB::AddBehavior()
{
cout<<"AddBehavior"<<endl;
}
void ConcreteDecoratorB::Operation()
{
AddBehavior();
m_Component->Operation();
}
main.cpp
#include "Component.h"
int main(int argc,char **argv)
{
//未装饰
Component *p1=new ConcreteComponent;
p1->Operation();
//DecoratorA
Component *p2=new ConcreteDecoratorA(p1);
p2->Operation();
//DecoratorB
Component *p3=new ConcreteDecoratorB(p1);
p3->Operation();
return 0;
}
执行结果:
可看到分别对ConcreteComponent的装饰。
时间: 2024-10-11 16:23:56