简体   繁体   English

装饰器未实现修饰的接口

[英]Decorator not implementing decorated interface

I have my small project where I wrapped object of one class with another class. 我有一个小项目,其中将一个类的对象与另一个类包装在一起。 Decorated class implements one interface but Decorator class does not implement it. 装饰类实现一个接口,但装饰器类不实现该接口。 I am curious whether it is still decorator pattern or some other pattern and "Decorator" class should be called Wrapper instead of Decorator in my project. 我很好奇它仍然是装饰器模式还是其他模式,在我的项目中应该将“ Decorator”类称为Wrapper而不是Decorator。

I have checked iluwatar github repository ( https://github.com/iluwatar/java-design-patterns/tree/master/decorator/src/main/java/com/iluwatar/decorator ) and tutorialspoint ( https://www.tutorialspoint.com/design_pattern/decorator_pattern ). 我已经检查了iluwatar github存储库( https://github.com/iluwatar/java-design-patterns/tree/master/decorator/src/main/java/com/iluwatar/decorator )和tutorialspoint( https:// www。 tutorialspoint.com/design_pattern/decorator_pattern )。 For example in iluwatar there is: Decorator: 例如在iluwatar中有:装饰器:

public class ClubbedTroll implements Troll

Decorated: 装饰:

public class SimpleTroll implements Troll

In both cases (iluwatar and tutorialspoint) there is common interface implementation in decorator and decorated class. 在这两种情况下(iluwatar和tutorialspoint),装饰器和装饰类中都有通用的接口实现。 Does it mean it is mandatory to call it decorator design pattern? 这是否意味着必须将其称为装饰器设计模式?

I'd say if you don't implement the interface in your decorator, then it simply cannot act like the original thing (decorated). 我想说的是,如果您没有在装饰器中实现该接口,则它根本无法像原始对象(装饰)那样工作。 If you're implementing the interface, you can use the decorator everywhere you could have done it with the original interface if classes. 如果要实现接口,则可以在原始接口(如果有类)中使用装饰器的任何地方。 That's why you have to use the interface. 这就是为什么您必须使用该界面。

If you just wrap the decorated, you've got a wrapper (delegation pattern). 如果只包装装饰物,则有一个包装纸(委托模式)。

The essense of Decrator pattern is to add additional functionality to an object without extending it. Decrator模式的本质是在不扩展对象的情况下向其添加其他功能。 The key word is additional , which means that the public API (or interface) of the object still stays the same. 关键字是extra ,这意味着对象的公共API(或接口)仍然保持不变。 Without this concept there's no point of using Decorator. 没有这个概念,就没有使用装饰器的意义。

So the question actually is "Does an object still provide the same public API without implementing an interface ?" 所以问题实际上是“一个对象是否仍在不实现interface情况下提供了相同的公共API?”

IMHO, it could be possible in some other language, but in Java it makes no sense, since you can not guarantee an object has the same public API and, therefore, rely on it. 恕我直言,可以用其他某种语言来实现,但是在Java中没有意义,因为您不能保证一个对象具有相同的公共API,因此只能依靠它。

As to Wrapper - this is another name for Adapter pattern . 对于包装器-这是适配器模式的另一个名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM