装饰者模式

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值