Decorator -- 装饰器模式: 丰富原接口的功能,并且不改动原先的接口。
// 创建Shape接口
public interface Shape {
void draw();
}
// 创建Shape接口的实体类
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Circle");
}
}
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Rectangle");
}
}
// 创建实现了Shape接口的抽象装饰类
public abstract class ShapeDecorator implements Shape {
protected Shape decoratedShape;
public ShapeDecorator(Shape decoratedShape) {
this.decoratedShape = decoratedShape;
}
public void draw() {
decoratedShape.draw();
}
}
// 创建扩展了 ShapeDecorator 类的实体装饰类, 在之前的功能上增加添加边线颜色的功能
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.");
}
}
// 测试类
public class DecoratorTest {
public static void main(String[] args) {
Shape circle = new Circle();
Shape redCircle = new RedShapeDecorator(circle);
Shape redRectangle = new RedShapeDecorator(new Rectangle());
circle.draw();
redCircle.draw();
redRectangle.draw();
}
}