装饰器设计模式Java覆盖方法问题

时间:2020-01-27 20:26:27

标签: java oop decorator

我需要帮助来了解装饰器的此示例:

    package design.decorator;
public class FillColorDecorator extends ShapeDecorator {
      protected Color color;
      public FillColorDecorator(Shape decoratedShape, Color color) {
            super(decoratedShape);
            this.color = color;
      }
      @Override
      public void draw() {
            decoratedShape.draw();
            System.out.println("Fill Color: " + color);
      }
      // no change in the functionality
      // we can add in the functionality if we like. there is no restriction
      // except we need to maintain the structure of the Shape APIs
      @Override
      public void resize() {
      decoratedShape.resize();
      }
      @Override
      public String description() {
      return decoratedShape.description() + " filled with " + color + " color.";
      }
      // no change in the functionality
      @Override
      public boolean isHide() {
      return decoratedShape.isHide();
      }
}

此示例摘自以下网站: https://dzone.com/articles/decorator-design-pattern-in-java

我只是不明白为什么他们会费心去实现功能不变的方法。例如:

return decoratedShape.isHide();

为什么这是必需的? 在我看来,删除它而不覆盖未更改的方法将可以很好地完成工作。

谢谢。

1 个答案:

答案 0 :(得分:1)

您必须实现它们,因为在这种情况下,ShapeDecorator只是实现了Shape的抽象类:它只是提供了一种统一的方式来存储经过修饰的Shape

package design.decorator;

public abstract class ShapeDecorator implements Shape {
      protected Shape decoratedShape;
      public ShapeDecorator(Shape decoratedShape) {
            super();
            this.decoratedShape = decoratedShape;
      }
}

如果您已经在ShapeDecorator类中这样做了,那么您将不需要它。