装饰器模式

一 定义
装饰器模式decorator pattern:动态的给一个对象增加一些额外的职责,在不改变本身功能的基础上增加一些额外的行为。
这里写图片描述
Component 抽象构件:是具体构件和抽象装饰类的共同父类,声明了在具体构件中的实现的业务方法。

ConcreteComponent 具体的组件对象:是抽象构件构件的子类,实现具体的操作,可以增加额外的操作方法。(说的直白一点:装饰器就是给它增加装饰的)。

Decoraton抽象装饰类:是抽象构构件类的子类,用于给具体的装饰器增加职责,由具体装饰器实现。

ConcreteDecorator具体装饰器类:实现具体要向被装饰对象添加的功能。

二 C++实现一个装饰器类
某公司开发了一个单独的记事本文本软件,使用的过程中要给这个某个文本文件增加滚动条功能,或者增加一个边框。使用了装饰器类。

Component.h

#pragma once


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

TextField.h

#pragma once 
#include <stdio.h>
#include <string>
#include "Component.h"

using namespace std;

class TextField:public Component  //定义一个文本框
{
private:
    std::string name;
    int width;
    int height;
public:
    TextField(int w, int h, std::string _name)
    {
        name = _name;
        width = w;
        height = h;
    }

    virtual ~TextField(){
    }

    void draw()
    {
        std::cout << name << ":" << width  << "*" << height << std::endl;
    }
};

Decorator.h

#pragma once 

#include "Component.h"

class Decorator:public Component  // 装饰器的抽象类
{
private:
    Component * component;
public:
    Decorator(){}

    Decorator(Component * _component){
        component = _component;
    }

    virtual ~Decorator(){
        delete component;
    }

    void draw(){
        component->draw();
    }
};

BorderDecorator.h

#pragma once 

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


class BorderDecorator:public Decorator  // 给文本框加一个边框
{
public:
    BorderDecorator(Component * w):Decorator(w){
    }

    virtual ~BorderDecorator(){
    }

    void draw(){
        Decorator::draw();
        printf("add a border\n");
    }
};

ScrollDecorator.h

#pragma once 

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


class ScrollDecorator:public Decorator  // 定义一个类,给文本框增加滚动条
{
public:
    ScrollDecorator(Component * w):Decorator(w){}

    void draw(){
        Decorator::draw();
        printf("add a scroll\n");
    }
};

main.cpp

#include <iostream>
#include <string>

#include "TextField.h"
#include "BorderDecorator.h"
#include "ScrollDecorator.h"


int main()
{
    Component * com = new BorderDecorator(new BorderDecorator(new ScrollDecorator
    (new TextField(80, 24, "my_field"))));
    com->draw();
    system("pause");
    return 0;
}

运行结果:
这里写图片描述
三总结
优点:
1 对于扩展一个对象功能,装饰器比继承更加灵活,不会导致类的个数急剧增加。
2 可以对一个对象进行多次装饰,通过使用不同具体具体装饰类以及这些装饰类的排列组合,可以创造出很多行为的组合,得到功能更能强大的对象。
3 可以根据需求增加新的具体构件类和装饰器类,原有的代码无需改变,符合开闭准则。

缺点:
1 进行系统设计的时候可能会产生很多小对象。
2 发生错误时排错困难。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值