Decorating Envelopes

The following text is a partial translation of the original English article, performed by ChatGPT (gpt-3.5-turbo) and this Jekyll plugin:

Sometimes Very often I need a class that implements an interface by making an instance of another class. Sound weird? Let me show you an example. There are many classes of that kind in the Takes Framework, and they all are named like *Wrap. It’s a convenient design concept that, unfortunately, looks rather verbose in Java. It would be great to have something shorter, like in EO for example.

看看Takes Framework中的RsHtml。它的设计看起来是这样的(只有一个主构造函数的简化版本):

现在,让我们来看看它扩展的RsWrap

正如您所见,这个“装饰器”除了“仅仅装饰”之外并不做任何其他事情。它封装了另一个Response并通过所有方法调用。

如果还不清楚的话,我将解释一下RsHtml的目的。假设您有文本并希望创建一个Response

不要在许多地方不断地使用装饰器的组合,而是使用 RsHtml

这非常方便,但是RsWrap太啰嗦了。有太多不做任何特殊处理的行,它们只是将所有方法调用转发给封装的Response

我们引入一个新概念,”decorators”,使用一个新关键字decorates,怎么样?

然后,为了创建一个对象,我们只需要调用:

我们在装饰器中没有任何新的方法,只有构造器。这些构造器的唯一目的是创建其他对象并对其进行封装。它们并不是真正的全功能对象,它们只是帮助我们创建其他对象的工具。

这就是为什么我会称它们为“装饰信封”。

这个想法可能看起来与工厂设计模式非常相似,但它没有静态方法,而我们正试图避免在面向对象编程中使用静态方法。

Translated by ChatGPT gpt-3.5-turbo/42 on 2023-12-16 at 15:51

sixnines availability badge   GitHub stars