设计模式—装饰模式
装饰器模式能够实现动态的为对象添加功能,是从一个对象外部来给对象添加功能。与代理模式、桥接模式有相似之处。
优点
- 装饰类和被装饰类可以独立发展, 而不会相互耦合。
- 装饰模式是继承关系的一个替代方案。
- 装饰模式可以动态地扩展一个实现类的功能 。
缺点
对于装饰模式记住一点就足够了: 多层的装饰是比较复杂的。 因此, 尽量减少装饰类的数量, 以便降低系统的复杂度。
使用场景
- 需要扩展一个类的功能, 或给一个类增加附加功能 。
- 需要动态地给一个对象增加功能, 这些功能可以再动态地撤销。
- 需要为一批的兄弟类进行改装或加装功能, 当然是首选装饰模式。
案例分析
- 接口
public interface Shape {
void draw();
}
- 接口实现1
/**
* 实现类1
*/
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Shape: Rectangle");
}
}
- 接口实现2
/**
* 实现类2
*/
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Shape: Circle");
}
}
- 抽象装饰器
/**
* 抽象装饰器
*/
public abstract class ShapeDecorator implements Shape {
protected Shape decoratedShape;
public ShapeDecorator(Shape decoratedShape) {
this.decoratedShape = decoratedShape;
}
@Override
public void draw() {
decoratedShape.draw();
}
}
- 扩展装饰器
/**
* 扩展装饰器
*/
public class RedShapeDecorator extends ShapeDecorator {
public RedShapeDecorator(Shape decoratedShape) {
super(decoratedShape);
}
@Override
public void draw() {
decoratedShape.draw();
setRedBorder(decoratedShape);
}
private void setRedBorder(Shape decoratedShape) {
System.out.println("Border Color: Red");
}
}
- Client
public class Client {
public static void main(String[] args) {
Shape circle = new Circle();
ShapeDecorator redCircle = new RedShapeDecorator(new Circle());
ShapeDecorator redRectangle = new RedShapeDecorator(new Rectangle());
System.out.println("Circle with normal border");
circle.draw();
System.out.println("\nCircle of red border");
redCircle.draw();
System.out.println("\nRectangle of red border");
redRectangle.draw();
}
}
输出结果:
Circle with normal border
Shape: CircleCircle of red border
Shape: Circle
Border Color: RedRectangle of red border
Shape: Rectangle
Border Color: Red
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏