是否有内置的Java类型可以保证execute(T t)方法?
看来对如下类型的需求是如此普遍,以至于类似的东西应该已经内置到 Java 中:
public interface Executer<T> {
void execute(T object);
}
然后它可以在其他类中使用,就像这个在对象上调用一堆执行器的简单示例一样。
class Handler<T> implements Executer<T> {
List<Executer<T>> executerList;
Handler(List<Executer<T>> executer) {
this.executerList = executer;
}
void execute(T t) {
for (Executer<T> executer : this.executerList) {
executer.execute(t);
}
}
}
是否有等效的内置类型或等效的公共库?这个概念有名字吗?
It seems the need for a type like the following would be so ubiquitous that something like it should be already built into Java:
public interface Executer<T> {
void execute(T object);
}
It can then be used in other classes like this trivial example that calls a bunch of executers on an object.
class Handler<T> implements Executer<T> {
List<Executer<T>> executerList;
Handler(List<Executer<T>> executer) {
this.executerList = executer;
}
void execute(T t) {
for (Executer<T> executer : this.executerList) {
executer.execute(t);
}
}
}
Is there a built-in type equivalent or a common library equivalent? Is there a name for this concept?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为这个概念的名称是策略模式。实际上,您正在封装一种算法,这使得将一种策略替换为另一种策略或应用多种策略变得更加容易。
这种设计模式非常容易实现,并且
execute
方法不需要仅采用特定类型的单个参数。因此,我怀疑您是否会找到内置的 Java 类型,但它是一种众所周知的设计模式。I think the name of the concept is the strategy pattern. Effectively you are encapsulating an algorithm, and this makes it easier to swap out one strategy for another or to apply a number of strategies.
This design pattern is very easy to implement, and the
execute
method need not take only a single argument of a specific type. As such, I doubt you will find a built-in Java type, but it is a well-known design pattern.我知道的最接近的是 Guava 的
函数
。我认为标准库中没有任何东西可以完全满足您的要求。
Runnable
有点接近,但不带参数。PS 我认为“函数”或“函子”正是这个概念的正确名称。
The closest I know of is Guava's
Function<F,T>
.I don't think there's anything in the standard library that does exactly what you're asking.
Runnable
is somewhat close, but takes no arguments.P.S. I think "function" or "functor" is exactly the right name for this concept.