设计模式(9)-装饰模式及实现
基本概念
提供了一种在运行时动态地为对象添加新功能的方法,通过创建一个装饰类来包装原始类。装饰类具有与原始类相同的接口,它内部包含一个指向原始对象的引用,并且可以根据需要包装额外的功能。这样,你可以通过组合不同的装饰类来构建出具有不同功能组合的对象。
优点:
装饰模式的优点包括避免了类爆炸问题,因为你可以通过组合少量的装饰类来实现各种功能组合。它也使得功能的增加和修改更加灵活,不会影响到其他部分的代码。
缺点:
装饰模式可能会导致增加很多小型的类,从而增加了代码的复杂性。
https://gitee.com/want-to-lose-another-30-jin/design-pattern-implementation
设计模式具体实现
角色
1、Component(抽象组件):定义一个接口,描述可以动态添加的职责。
2、ConcreteComponent(具体组件):实现Component接口的具体类。
3、Decorator(抽象装饰者):抽象类,实现Component接口,并持有Component接口的一个实例。
4、ConcreteDecorator(具体装饰者):具体实现Decorator类,添加具体的职责。
java实现
package shejimoshi.zhuangshimoshi;
// 抽象组件
public interface Shape {
void draw();
}
package shejimoshi.zhuangshimoshi;
// 具体组件
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Drawing a circle.");
}
}
package shejimoshi.zhuangshimoshi;
// 抽象装饰者
public abstract class ShapeDecorator implements Shape {
protected Shape decoratedShape;
public ShapeDecorator(Shape decoratedShape) {
this.decoratedShape = decoratedShape;
}
@Override
public void draw() {
decoratedShape.draw();
}
}
package shejimoshi.zhuangshimoshi;
// 具体装饰者
public class RedShapeDecorator extends ShapeDecorator {
public RedShapeDecorator(Shape decoratedShape) {
super(decoratedShape);
}
@Override
public void draw() {
super.draw();
setColor();
}
private void setColor() {
System.out.println("Painting the shape red.");
}
}
package shejimoshi.zhuangshimoshi;
public class client {
public static void main(String[] args) {
Shape circle = new Circle();
circle = new RedShapeDecorator(new Circle());
circle.draw(); // 输出:Drawing a circle. Painting the shape red.
}
}
c++实现
#include<iostream>
// 抽象组件
class Shape {
public:
virtual void draw() = 0;
virtual ~Shape() {}
};
// 具体组件
class Circle : public Shape {
public:
void draw() override {
std::cout << "Drawing a circle." << std::endl;
}
};
// 抽象装饰者
class ShapeDecorator : public Shape {
protected:
Shape* decoratedShape;
public:
ShapeDecorator(Shape* shape) : decoratedShape(shape) {}
void draw() override {
if (decoratedShape) decoratedShape->draw();
}
};
// 具体装饰者
class RedShapeDecorator : public ShapeDecorator {
public:
RedShapeDecorator(Shape* shape) : ShapeDecorator(shape) {}
void draw() override {
ShapeDecorator::draw();
setColor();
}
private:
void setColor() {
std::cout << "Painting the shape red." << std::endl;
}
};
// 客户端代码
int main() {
Shape* circle = new Circle();
Shape* redCircle = new RedShapeDecorator(circle);
redCircle->draw(); // 输出:Drawing a circle. Painting the shape red.
delete redCircle; // 释放装饰者
delete circle; // 释放具体组件
return 0;
}