gpt4 book ai didi

java - 装饰器设计模式java重写方法问题

转载 作者:行者123 更新时间:2023-12-02 09:04:23 26 4
gpt4 key购买 nike

我需要帮助理解装饰器的这个示例:

    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();

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

谢谢。

最佳答案

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

package design.decorator;

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

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

关于java - 装饰器设计模式java重写方法问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59938437/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com