1、什么是装饰者模式?
动态地将责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的替代方案。
2、优缺点
优点
a、在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责
b、需要动态地给一个对象增加功能,这些功能也可以动态地被撤销。
c、当不能采用继承的方式对系统进行扩充或者采用继承不利于系统扩展和维护时
缺点
a、由于使用装饰模式,可以比使用继承关系需要较少数目的类。使用较少的类,当然使设计比较易于进行。但是,在另一方面,使用装饰模式会产生比使用继承关系更多的对象。更多的对象会使得查错变得困难,特别是这些对象看上去都很相像。
3、结构
4、代码
#pragma once
#include <string>
class Person
{
public:
Person() = default;
Person(std::string name);
virtual void Show();
private:
std::string name_;
};
#include "Person.h"
#include <iostream>
Person::Person(std::string name)
{
this->name_ = name;
}
void Person::Show()
{
std::cout << "装饰的" << name_ << std::endl;
}
#pragma once
#include "Person.h"
class Finery :public Person {
protected:
Person* component_;
public:
Finery() = default;
void Decorator(Person* component);//穿衣服函数
void Show();
};
#include "Finery.h"
void Finery::Decorator(Person * component)
{
this->component_ = component;
}
void Finery::Show()
{
if (component_ != NULL) {
component_->Show();
}
}
#pragma once
#include "Finery.h"
#include <iostream>
//具体服装
class Tshirts :public Finery {
public:
Tshirts() {};
void Show() {
std::cout << "Tshirts";
Finery::Show();
}
};
class Sneakers :public Finery {
public:
Sneakers() {};
void Show() {
std::cout << " Sneakers";
Finery::Show();
}
};
#include "Person.h"
#include "Tshirts.h"
#include "Finery.h"
int main() {
Person* xc = new Person("小菜");
std::cout << "first style:" << std::endl;
Finery* ts = new Tshirts();
Finery* sn = new Sneakers();
ts->Decorator(xc);//小菜穿第一件衣服
sn->Decorator(ts);//小菜穿第二件衣服
sn->Show();
getchar();
return 0;
}