Is there a library out there that already provides the interfaces we need for the command pattern in Java?
For example:
public interface Func1<T,R> { public R execute(T input); }
public interface Func2<T1,T2,R> { public R execute(T1 input1, T2 input2); }
public interface Predicate1<T> { public boolean execute(T input); }
....
Thanks.
In a classic implementation, the command pattern requires implementing four components: the Command, the Receiver, the Invoker, and the Client.
In object-oriented programming, the command pattern is a behavioral design pattern in which an object is used to encapsulate all information needed to perform an action or trigger an event at a later time. This information includes the method name, the object that owns the method and values for the method parameters.
A Command Pattern says that "encapsulate a request under an object as a command and pass it to invoker object. Invoker object looks for the appropriate object which can handle this command and pass the command to the corresponding object and that object executes the command". It is also known as Action or Transaction.
The command pattern should be used when: You need a command to have a life span independent of the original request, or if you want to queue, specify and execute requests at different times. You need undo/redo operations. The command's execution can be stored for reversing its effects.
Guava has your first and third interfaces (called Function
and Predicate
). Your second one, IMHO, is not useful, because you would just have to combine T1 and T2 in a single object, and use the first interface instead.
More interesting, Guava also has a whole lot of methods using these two interfaces, like Iterables.any(Iterable, Predicate)
, Iterables.transform(Iterable, Function)
, etc.
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