gpt4 book ai didi

java - 装饰器模式 - 添加接口(interface)中未定义的功能

转载 作者:行者123 更新时间:2023-12-02 02:18:39 28 4
gpt4 key购买 nike

关于使用此模式是否有任何硬性规定,或者它仅仅是为了在不使用继承的情况下在方法调用中实现附加功能?

我修改了下面的示例,该示例是我从 SO 帖子中获取的,以展示我正在考虑的内容。

 public interface Coffee {
public double getCost();
public String getIngredients();
}
public class SimpleCoffee implements Coffee {
@Override
public double getCost() {
return 1;
}
@Override
public String getIngredients() {
return "Coffee";
}
}

public class CoffeeDecorator implements Coffee {
protected final Coffee decoratedCoffee;

public CoffeeDecorator(Coffee c) {
this.decoratedCoffee = c;
}
@Override
public double getCost() {
//you can add extra functionality here.
return decoratedCoffee.getCost();
}
@Override
public String getIngredients() {
//you can add extra functionality here.
return decoratedCoffee.getIngredients();
}

public boolean methodNotDefinedInInterface() {
//do something else
return true;
}
}

考虑到上面的例子,是否可行:

a) 只要您认为合适,就使用简单的咖啡,无需装饰

b) 将 Coffee 接口(interface)中未定义的附加功能添加到装饰器对象,例如 methodNotDefinedInInterface()

有人还可以解释一下组合在哪里进入这种模式,因为 SimpleCoffee 是可以独立存在的东西,但它似乎是实际上“拥有”任何对象的装饰器。

尽管没有 SimpleCoffee 类(或 Coffee 的一些具体实现),装饰器没有任何目的,因此聚合似乎不是这里发生的事情。

最佳答案

description of the pattern包含意图,这使得该模式的用途非常清楚:

The decorator pattern can be used to extend (decorate) the functionality of a certain object statically, or in some cases at run-time, independently of other instances of the same class, provided some groundwork is done at design time.

至于“硬性规则”——我一般认为模式中根本不存在“硬性规则”。就像,如果你不完全按照 GoF 描述的那样实现,就不会有“模式警察”惩罚你。唯一的一点是,如果您遵循经典指南,其他开发人员在识别您的代码中的模式时会遇到更少的问题。

从我的角度来看,你的例子非常好。

SimpleCoffee 不是装饰器,因此没有组合。 CoffeeDecoratordecoratedCoffee 作为组件(这里有您的组合)

关于java - 装饰器模式 - 添加接口(interface)中未定义的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48881314/

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