装饰器模式属于结构型模式,它允许向一个现有的对象添加新的功能,同时又不改变其结构。
大致的结构如下图:
Target:我们的目标类
TargetDecorator:装饰器类,它和目标类共同实现了抽象接口。
调用的时候,我们直接调用装饰器类就可以了,在这个类里面我们把目标类的代码拓展一些功能。
具体的示例如下:
步骤1:
创建一个接口。
Shape.java
public interface Shape {
void draw();
}步骤2:
创建实现接口的实体类。
Rectangle.java
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Shape: Rectangle");
}
}Circle.java
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Shape: Circle");
}
}步骤3:
创建实现了Shape接口的抽象装饰类。
ShapeDecorator.java
public abstract class ShapeDecorator implements Shape {
protected Shape decoratedShape;
public ShapeDecorator(Shape decoratedShape){
this.decoratedShape = decoratedShape;
}
public void draw(){
decoratedShape.draw();
}
}步骤4:
创建扩展了ShapeDecorator类的实体装饰类。
RedShapeDecorator.java
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");
}
}步骤5:
使用RedShapeDecorator来装饰Shape对象。
DecoratorPatternDemo.java
public class DecoratorPatternDemo {
public static void main(String[] args) {
Shape circle = new Circle();
Shape redCircle = new RedShapeDecorator(new Circle());
Shape 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();
}
}步骤6:
验证输出。
Circle with normal border
Shape: Circle
Circle of red border
Shape: Circle
Border Color: Red
Rectangle of red border
Shape: Rectangle
Border Color: Red
装饰器模式详解
本文介绍装饰器模式,一种允许在不改变对象结构的前提下为其添加新功能的设计模式。通过具体示例,展示了如何通过装饰器模式为不同的形状添加红色边框。
1389

被折叠的 条评论
为什么被折叠?



