Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interfaces for Command Pattern in Java

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.

like image 897
Dejas Avatar asked May 01 '12 22:05

Dejas


People also ask

What would you use to implement the Command pattern?

In a classic implementation, the command pattern requires implementing four components: the Command, the Receiver, the Invoker, and the Client.

What design principles is the Command pattern using?

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.

What is the other name given for the command design pattern?

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.

When should I use Command pattern?

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.


1 Answers

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.

like image 105
JB Nizet Avatar answered Oct 05 '22 11:10

JB Nizet