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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With