java装饰器模式_Java 8的装饰器模式

java装饰器模式

java装饰器模式

最近的一篇文章中,我描述了装饰器模式如何拯救了我的一天。 我给出了一个小代码段,其中包含创建装饰器的最简单方法,但承诺Java 8会有更好的方法。

这里是:用Java 8装饰

HyperlinkListener listener = this::changeHtmlViewBackgroundColor;
listener = DecoratingHyperlinkListener.from(listener)
	.onHoverMakeVisible(urlLabel)
	.onHoverSetUrlOn(urlLabel)
	.logEvents()
	.decorate(l -> new OnActivateHighlightComponent(l, urlLabel))
	.decorate(OnEnterLogUrl::new);

我将在文章的其余部分中说明如何到达那里。

在GitHub上创建了一个小示例项目,我将从这里重复引用。 我只建议您检查一下它,因为它提供了更多详细信息。 它是公共领域,因此可以不受限制地使用该代码。

为了继续我的上一篇文章,它使用了Swing的HyperlinkListener作为装饰的基础。 由于该接口不是通用接口,并且仅具有一个仅带有一个参数的方法(对于lambda表达式而言非常好!),因此具有使接口保持简单的另一优点。

总览

像其他帖子一样,该帖子也没有尝试教授模式本身。 (不过,我找到了另一个很好的解释。)相反,它推荐了一种在Java 8中实现它的方法,以使其使用起来非常方便。 因此,该帖子严重依赖Java 8功能,尤其是默认方法lambda表达式

这些图只是草图,并省略了许多细节。 更完整的是容易找到的

香草

装饰图案

在模式的通常实现中,存在一个接口(上面称为Component ),该接口将通过“常规”类以及所有装饰器以常规方式实现。

抽象装饰器类

装饰器通常从中间抽象基类( AbstractDecorator )继承,从而简化了实现。 它使用另一个组件作为构造函数参数,并通过将所有调用转发给接口来实现接口本身。 因此,装饰组件的行为不变。

现在由子类来实际更改它。 他们通过有选择地重写那些他们想改变其行为的方法来做到这一点。 这通常包括对装饰组件的调用。

装饰器的创建

通常,不使用特殊技术来创建装饰器。 只是简单的构造函数。 对于复杂的装饰器,您甚至可以使用工厂。

我是静态构造方法的忠实拥护者,因此我使用它们并将构造方法设为私有。 为了使这些方法的调用者不了解细节,我将这些方法的返回类型声明为Component ,而不是装饰器的更详细类型。 例如,这可以在LogEventsToConsole中看到。

我的建议改变了装饰器的创建方式。

使用Java 8

装饰器模式Java8

要使用Java 8的所有功能,我建议为所有装饰器添加一个特殊的接口DecoratingComponent 。 装饰器的抽象超类实现了该接口,但像以前一样,仅保留对Component的引用。

重要的是要注意,由于新接口的定义(请参见下文),混凝土装饰器没有任何变化。 它们在模式的两种实现中都完全相同。 抽象类实际上也没有任何变化(请参见下文),因此切换到该解决方案不会产生明显的成本。

新介面

新接口DecoratingComponent扩展了基本组件接口,并为装饰器提供了工厂方法。 这些是静态或默认/防御方法(因此它们已经实现,如果可以的话将是最终方法),并且不应声明任何抽象方法。 这样,新接口不会在继承树后面的实现上增加额外的负担。

关于以下代码示例:通用示例仅为该帖子创建。 涉及超链接侦听器的对象来自演示应用程序。 最值得注意的是DecoratingHyperlinkListener ( 到源文件链接),它扩展了Swing的HyperlinkListener

方法

接口本身实际上非常简单,由三种类型的方法组成。

适配器

为了快速从Component移到DecoratingComponent ,接口应该有一个静态方法,该方法采用第一个方法,然后返回后者。 由于DecoratingComponent扩展了Component且未添加任何抽象方法,因此这很简单。 只需创建一个匿名实现,并将所有调用转发到已适配的component

通用方法如下所示:

静态适配器方法

static DecoratingComponent from(Component component) {
	DecoratingComponent adapted = new DecoratingComponent() {
		@Override
		public SomeReturn someMethod(SomeArgument argument) {
			return component.someMethod(argument);
		}

		// ... more methods here ...
	};
	return adapted;
}

DecoratingHyperlinkListener情况下,它要容易得多,因为它是一个功能接口,因此可以使用lambda表达式:

'DecoratingHyperlinkListener'中的静态适配器方法

static DecoratingHyperlinkListener from(HyperlinkListener listener) {
	return event -> listener.hyperlinkUpdate(event);
}
通用装饰

这是接口的基本方法:

default DecoratingComponent decorate(
		Function<? super DecoratingComponent, ? extends DecoratingComponent>
			decorator) {

	return decorator.apply(this);
}

它从一个装饰组件到另一个装饰组件接受一个函数作为参数。 它将功能应用于自身以创建装饰实例,然后将其返回。

可以在整个代码中使用此方法,以一种简单易读的方式装饰任何组件:

用'DecoratingComponent'装饰

Component some = ...;
DecoratingComponent decorated = DecoratingComponent
	// create an instance of 'DecoratingComponent' from the 'Component'
	.from(some)
	// now decorate it
	.decorate(component -> new MyCoolComponentDecorator(component, ...));

// if you already have an instance of 'DecoratingComponent', it get's easier
decorated = decorated
	.decorate(component -> new MyBestComponentDecorator(component, ...));

// constructor references are even clearer (but cannot always be used)
decorated = decorated.decorate(MyBestComponentDecorator::new);
混凝土装饰

您还可以添加使用具体装饰器装饰实例的方法:

'DecoratingHyperlinkListener'中的混凝土装饰

default DecoratingHyperlinkListener logEvents() {
	return LogEventsToConsole.decorate(this);
}

default DecoratingHyperlinkListener onHoverMakeVisible(JComponent component) {
	return OnHoverMakeComponentVisible.decorate(this, component);
}

它们使装饰非常简洁易读:

用'DecoratingComponent'装饰

DecoratingComponent decorated = ...
decorated = decorated.logEvents();

但是,是否应真正添加这些方法仍有待商de。 尽管它们非常方便,但是当它们创建循环依赖项时,可以对它们进行强烈的争论。 装饰器不仅知道接口(它们通过抽象超类间接实现),现在接口也知道其实现。 通常,这是刺激性的代码气味。

最终召集尚未结束,但我建议采取务实的中间方式。 我让该接口知道存在于同一包中的实现。 这将是通用的,因为它们没有引用其余代码中的任何具体内容。 但是我不会让我知道我在系统深处创建的每个疯狂装饰器。 (当然,除非将其称为the_kraken,否则我不会将所有这些装饰器都添加到同一包中。)

为什么需要额外的接口?

是的,是的,所有那些Java 8功能都非常不错,但是您不能简单地将这些方法添加到AbstractDecorator吗? 好问题!

当然,我可以在这里添加它们。 但由于两个原因,我不喜欢这种解决方案。

单一责任原则

首先,这将模糊类的职责。 新接口负责装饰Component实例,抽象超类负责启用装饰器的轻松实现。

这些不是相同的事物,并且由于相同的原因它们不会改变。 每当必须包含新的装饰器时,新的界面可能就会更改。 每当Component更改时,抽象类都会更改。

类型层次结构

如果将这些方法添加到AbstractDecorator ,则只能在此类实例上调用它们。 因此,所有装饰器都必须从该类继承,这限制了将来实现的范围。 谁知道,也许出现了一些非常好的理由,为什么另一个类不能成为AbstractDecorator

更糟糕的是,所有装饰器都必须公开它们是AbstractDecorator的事实。 突然有一个抽象类,它只是为了简化实现而创建的,它遍及整个代码库。

其他差异

除了引入新接口之外,模式的变化不会有太大变化。

对抽象装饰器类的更改

如果可以访问该类,则应让它实现DecoratingComponent而不是Component 。 由于没有引入新的抽象方法,因此不需要进一步的更改。 上面的UML图中显示了这一点。

如果您不能更改类,则装饰器将仅实现Component 。 这将使您避免使用其构造函数来创建将组件映射到装饰组件的函数。 由于需要将该函数作为decorate方法的参数,因此必须将该方法更改为如下所示:

通用装饰

// note the more general second type of the 'Function' interface
default DecoratingComponent decorate(
		Function<? super DecoratingComponent, ? extends Component> decorator) {

	// create the decorated instance as before
	Component decorated = decorator.apply(this);
	// since it is no 'DecoratingComponent' use 'from' to turn it into one
	return from(decorated);
}
装饰者的变化

无需更改这些类。 当然,除非您是使用静态工厂方法的那些疯狂的人之一。 比您必须确保它们将其返回类型声明为DecoratingComponent否则您将处于与抽象超类无法实现新接口的情况相同的情况。 如果您不能更改装饰器类,则此处使用相同的解决方案。

因此,让我们从上方再次查看代码段:

用Java 8装饰

// create a 'HyperlinkListener' with a method reference
HyperlinkListener listener = this::changeHtmlViewBackgroundColor;
// decorate that instance with different behaviors
// (note that each call actually returns a new instance
//  so the result has to be assigned to a variable)
listener = DecoratingHyperlinkListener
	// adapt the 'HyperlinkListener' to be a 'DecoratingHyperlinkListener'
	// (looks better if it is not on its own line)
	.from(listener)
	// call some concrete decorator functions
	.onHoverMakeVisible(urlLabel)
	.onHoverSetUrlOn(urlLabel)
	.logEvents()
	// call the generic decorator function with a lambda expression
	.decorate(l -> new OnActivateHighlightComponent(l, urlLabel))
	// call the generic decorator function with a constructor reference
	.decorate(OnEnterLogUrl::new);

反射

我们了解了如何使用Java 8的静态和默认接口方法为装饰器模式创建流畅的API。 它使代码同时更加简洁和可读性,同时又不干扰模式的机制。

正因为如此,我们使用默认的方法来创建特质有关其作者Brian Goetz写道

了解默认方法的关键是,主要的设计目标是接口演变,而不是“将接口转变为(中等)特征”。

抱歉,Brian,这太诱人了。 ;)

对装饰器模式有一些见解? 想要改善我的想法还是批评它? 然后发表评论! 并且不要忘记在GitHub上检查代码

翻译自: https://www.javacodegeeks.com/2015/01/the-decorator-pattern-with-java-8.html

java装饰器模式

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值