Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 770
Jeff Axelrod Avatar asked Jan 25 '12 17:01

Jeff Axelrod


2 Answers

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.

like image 78
Michael McGowan Avatar answered Sep 21 '22 20:09

Michael McGowan


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.

like image 44
NPE Avatar answered Sep 23 '22 20:09

NPE