设计模式之——装饰模式

shape.h

#ifndef SHAPE_H
#define SHAPE_H

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

#endif // SHAPE_H

rectangle.h

#ifndef RECTANGLE_H
#define RECTANGLE_H

#include "shape.h"

class Rectangle : public Shape
{
public:
    Rectangle(){}
    void draw()
    {
        qDebug() << "Shape: Rectangle";
    }
};

#endif // RECTANGLE_H

shapeDecorator.h

#ifndef SHAPEDECORATOR_H
#define SHAPEDECORATOR_H

#include "shape.h"

//创建实现了 Shape 接口的抽象装饰类。
class ShapeDecorator : public Shape
{
public:
    ShapeDecorator(Shape *decoratedShape):m_decoratedShape(decoratedShape){}
    virtual void draw(){m_decoratedShape->draw();}

private:
    Shape *m_decoratedShape;
};

#endif // SHAPEDECORATOR_H

redShapeDecorator.h

#ifndef REDSHAPEDECORATOR_H
#define REDSHAPEDECORATOR_H
#include <QtDebug>
#include "shape.h"
#include "shapeDecorator.h"

//创建扩展了 ShapeDecorator 类的实体装饰类。
class RedShapeDecorator : public ShapeDecorator
{
public:
    RedShapeDecorator(Shape *shape): ShapeDecorator(shape){}
    void draw()
    {
        ShapeDecorator::draw();
        setRedBorder();
    }
private:
    void setRedBorder()
    {
        qDebug() << "Border Color: Red";
    }
};

#endif // REDSHAPEDECORATOR_H

main

#include <QApplication>
#include <QtDebug>
#include "shape.h"
#include "shapeDecorator.h"
#include "redShapeDecorator.h"
#include "rectangle.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    ShapeDecorator *redRectangle = new RedShapeDecorator(new Rectangle());
    redRectangle->draw();

    return a.exec();
}

UML
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值