装饰器模式
允许向一个现有的对象添加新的功能,同时又不改变其结构。
// 形状接口
public interface Shape {
void draw();
}
// 圆形
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("画圆");
}
}
// 方形
public class Square 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;
}
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("外观颜色: 红色");
}
}
// 使用示例
public class Demo {
public static void main(String[] args) {
Shape circle = new Circle();
Shape square = new Square();
Shape redCircle = new RedShapeDecorator(new Circle());
Shape redSquare = new RedShapeDecorator(new Square());
circle.draw();
square.draw();
redCircle.draw();
redSquare.draw();
}
}