Is there a built-in Java type that guarantees an e

2019-06-18 21:58发布

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?

2条回答
戒情不戒烟
2楼-- · 2019-06-18 22:27

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.

查看更多
不美不萌又怎样
3楼-- · 2019-06-18 22:29

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.

查看更多
登录 后发表回答