装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。
一个接口
public interface Shape {
void draw();
}
接口实现类
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("形状:圆");
}
}
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("形状:长方形");
}
}
装饰器抽象类也实现形状接口
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("边框颜色:红色");
}
}
使用 RedShapeDecorator 来装饰 Shape 对象
public class DecoratorPatternDemo {
public static void main(String[] args) {
Shape circle = new Circle();
ShapeDecorator redCircle = new RedShapeDecorator(circle);
Rectangle rectangle = new Rectangle();
ShapeDecorator redRectangle = new RedShapeDecorator(rectangle);
System.out.println("正常边框的圆");
circle.draw();
System.out.println("n红色边框圆");
redCircle.draw();
System.out.println("n正常边框的长方形");
rectangle.draw();
System.out.println("n红色边框长方形");
redRectangle.draw();
}
}
结果:
正常边框的圆 形状:圆 红色边框圆 形状:圆 边框颜色:红色 正常边框的长方形 形状:长方形 红色边框长方形 形状:长方形 边框颜色:红色
参考:
https://www.runoob.com/design-pattern/design-pattern-intro.html



