Jeff Axelrod
Jeff Axelrod

Reputation: 28188

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?

Upvotes: 6

Views: 196

Answers (2)

Michael McGowan
Michael McGowan

Reputation: 6608

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.

Upvotes: 4

NPE
NPE

Reputation: 500673

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.

Upvotes: 2

Related Questions