Is there a built-in Java type that guarantees an execute(T t) method?

拜拜、爱过 提交于 2019-12-23 09:37:53

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/9007008/is-there-a-built-in-java-type-that-guarantees-an-executet-t-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!