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