How to implement this code using lambda expressions in Java? - java

I have a software specification document for a specific library in java which helps collecting data from a biosensor and has a class called 'Patch'. The document specifies:
Following is the constructor of Patch class:
Patch(JSONObject options, (JSONObject)->onDiscovery,(JSONObject)->ondata,(JSONObject)->onStatus)
Where
JOSNObject options: options settings for the object
(JSONObject)->onDiscovery: Callback for receiving the sensor info as a JSONObject,
(JSONObject)->ondata: Callback for receiving the sensor data as a JSONObject,
(JSONObject)->onStatus: Callback for receiving the global errors as a JSONObject
It should be called as
Patch patch=newPatch(jsonConfigObject, discoveryObject, streamObject, status);
The concerned fellow stated that these callbacks shall be just lambda expressions.
Now what I understand is:
Constructor takes 4 args:
An empty JSON object,
Callback function reference
Callback function reference
Callback function reference
Am new to Callback implementation so am not able to figure out:
how shall I implement this one in my code?
Do I have to create the functional interfaces for each of those callback methods?
Lets say I have just imported the library, what shall I do next?

The objective of lambda expressions is to denote methods that the Patch-object can call (back) at certain events. In contrast to other programming languages it was not possible to pass functions as parameters to constructors or methods in Java. Thus it was necessary to create an object of a class that implements a certain interface (or is otherwise known to have a certain method by type) and to pass it to the method or constructor as a parameter. The method can then be called at the passed object when the event occurs.
The functional interface is already there. You do not need to create it by yourself. It has been already used in the signature of the constructor of Patch (the types of the last three parameters to the constructor). Functional interfaces are types which have exactly one abstract method that has to be overridden.
Lets suppose the functional interface looks like this:
interface Callback { // could of course have a different name
public void call(JSONObject o);
}
It is not necessary to add the #FunctionalInterface-annotation. It would only prevent the interface from later modifications, namely adding further abstract methods.
It seems reasonable to assume that the abstract method does not have a return value (but you need to check this. When you use lambda expressions you do not need to know what the actual method name (here call) is.
Although most handy it is not necessary to call the constructor with lambda expressions for the last three parameters. Other possibilities include a method reference (using ::), anonymous classes, and instantiating a newly defines class.
Of course you need to know what should happen when the three events occur. Lets say that you have already three methods that provide the necessary functionality. Probably a JSONObject that contains information about the event is necessary to do something useful.
class Main {
static void onDiscovery(JSONObject o) {...}
static void onData(JSONObject o) {...}
static void onStatus(JSONObject o) {...}
}
It is not necessary that the three methods have exactly these names nor that they are static.
In the main method of this class (or somewhere else) could happen:
public static void main(String[] args) {
JSONObject o = // ...
Patch p = new Patch(o,
(x) -> Main.onDiscovery(x), // (1) lambda expr. (Main. can be omitted)
Main::onData, // (2) method reference
new Callback() { // (3) anonymous inner class
public void call(JSONObject x) {
Main.onStatus(x);
}
});
//...
}
(1)-(3) show alternative ways to pass an object of type Callback.
(1) has the advantage that shorter implementations could go right here instead of calling onDiscovery(x). If you have more than one statement you need curly brackets around the statements and ";" after each statement:
(x) -> {
System.out.println("discovery event");
System.out.println(x.getXYZ());
// ...
}
(2) has the advantage to be super concise. If you do not have a static method to reference, a object reference can also be used to denote the object on which the method should be called.
(3) anonymous inner classes are would normally not be used anymore for functional interfaces. If the interface / abstract class has more abstract methods but one it is still necessary to use anonymous inner classes.
class Main {
void onData(JSONObject o) { ... }
// ...
public static void main(String[] args) {
var m = new Main();
var o = new JSONObject(); // or whatever
var p = new Patch(o,
(x) -> m.onDiscovery(x),
m::onData;
new Callback() {
public void call(JSONObject x) {
m.onStatus(x);
}
});
}
}

Related

Java 8 Method Reference more than one different constructors

I'm trying to write a method that takes a constructor of a Runnable class and runs it in a certain way, according to the constructor that was input.
So I want to be able to do something like this:
executeInParallel(someRunnable::new)
executeInParallel(someOtherRunnable::new)
My question is how do I define the executeInParallel method in order to be able to pass any of the Runnable constructors I've defined in the parameters? Essentially my question is in order to do that what how do I define this method?
void executeInParallel(??){ ... }
It seems that I can only have methods that adhere to a Functional Interface as parameters though, so I can't define executeInParallel with a single parameter that accepts more than one xRunnable::new constructors Is there a way for me to do this without using some sort of a Factory pattern?
I want to make clear that the reason I want to do this is that I want to pass in constructors and not instances. I can't generate the instance outside executeInParallel, it has to be generated inside that method. I also want to pass in different constructors that take different parameters
Thank you in advance
EDIT
Sorry, I made the question a little more clear hopefully.
Your executeInParallel() method accepts something that will generate a Runnable, so its signature should be executeInParallel(Supplier<? extends Runnable> runnableFactory)
Then, you can call it with any lambda or method reference that can return an instance of any class that implements Runnable.
Possible usages :
// Ex 1 :
class MyJob implements Runnable {
public void run() {...}
}
executeInParallel(() -> new MyJob());
executeInParallel(MyJob::new);
// Ex 2 :
class MyJobWithParams implements Runnable {
public MyJobWithParams(String param1, int param2) { ... }
public void run() {...}
}
executeInParallel( () -> new MyJobWithParams("Hello",42) );
// You cannot use method references here
// Ex 3 :
class RunnableFactory {
public static Runnable makeRunnable() {
return new MyJob(); // which is a Runnable, see above
}
}
executeInParallel( () -> RunnableFactory.makeRunnable() );
executeInParallel( RunnableFactory::makeRunnable );
Also, you state that you only want Runnable constructors to be passed to the method. This can be done via a method reference (but only for a no-arg constructor), or via a lambda expression (like in example #1 and #2 above).

Questions on classes extending from a base class (Java)

I'm a beginner in Java trying to write a system of party quests for a game that I'm currently writing and I have a few questions I'd like to be answered. I've already gone around and asked other people, but they're not familiar in Java.
In the past I'd tried making a bunch of classes and accessing them with multiple get methods. I found that incredibly tedious to write and thought I could unify them under an abstract class/implemented class. Thus, the code looked more like this ...
DynastyPQInterface pq = new CustomPQ // or ....
DynastyPQInterface pq = new OtherCustomPQ
Of course, this presented difficulties such as being only able to use implemented methods. It didn't allow me to access the class' exclusive methods that I might want to use later on.
Ultimately, what I want to do is to be able to use a single get method to return any of these derived classes, but still retain the ability to just universally use the get method to call methods that they have in common, such as execute, create, end, while simultaneously allowing me to reach out to their exclusive methods specifically. Is there a way to do that, or is it impossible?
If it's still not clear ...
The code I have write now is a base class that is extended to the other classes in the manner ...
DynastyPQ (base) -> methods include (run(), execute(), end())
CustomAPQ (inherited from DynastyPQ) -> (has exclusive methods like getPoints())
CustomBPQ (inherited from DynastyPQ) -> (has exclusive methods like revivePlayer())
I want to write a get method so to rid myself of multiple. What I have right now is ...
DynastyPQ dynastyPQ;
DynastyPQ getPQ() {
return dynastyPQ;
}
void setPQ(DynastyPQ pq) {
dynastyPQ = pq;
}
Doing this ...
DynastyPQ pq = new CarnivalPQ();
I can only access DynastyPQ's methods rather than Carnival's methods.
Is there a way to access the exclusive methods while universally being able to execute the four base functions without regard to the type of class, or did I miss something earlier?
tl;dr -> I want one get method that universally returns all classes that inherit from class X; however, I want to be able to access each class's exclusive methods.
You can probably just cast the object to the derived class:
DynastyPQ pq = new CustomAPQ();
((CustomAPQ)pq).customAPQmethod();
If you don't know what is the dynamic type (the type you used after the new operator), you can use the instanceof keyword:
DynastyPQ pq = getPQ();
if (pq instanceof CustomAPQ) {
CustomAPQ a = (CustomAPQ)pq;
a.customAPQmethod();
} else if (pq instanceof CustomBPQ) {
CustomBPQ b = (CustomBPQ)pq;
b.customBPQmethod();
} else {
// Neither a CustomAPQ nor a CustomBPQ.
}
If you don't want to do that, you can use polymorphism:
class DynastyPQ {
final void run() {
// code.
}
final void execute() {
// code.
}
final void create() {
// code.
}
void specific1() {}
void specific2() {}
}
class CustomAPQ extends DynastyPQ {
#Override
void specific1() {
// do stuff specific to CustomAPQ.
}
#Override
void specific2() {
// do stuff specific to CustomAPQ.
}
}
class CustomBPQ extends DynastyPQ {
#Override
void specific1() {
// do stuff specific to CustomBPQ.
}
#Override
void specific2() {
// do stuff specific to CustomBPQ.
}
}
Now, you can do:
DynastyPQ pq = new CustomAPQ();
pq.specific1();
The called method will be CustomAPQ::specific1(). If specific1() was not declared in CustomAPQ, then, it will just do nothing.
Other than #CelineNOEL suggested it is not possible. Because you declared a class of type DynastyPQ, you can call only methods defined inside that class. In the moment you want to call specific method, not shared one, you know from which class it is and you can use casting to call that specific method.
((CustomAPQ)pq).customAPQmethod()
Shared methods you are using in code, when you don't know which class should execute same peace of code(or you want it to execute it different if you override share methods in every sub-class), and you delegate it to be resolved in runtime. So reconsider your design and in base class put methods that needs to be called dynamically. All other methods you are sure are specific for one class put only in that class. On that way your code will be cleaner and you will not mess thing that should be separated.

Can we write a function in Java that takes another function signature as a parameter and executes it? [duplicate]

This may be something common and trivial, but I seem to be having trouble finding a concrete answer. In C# there is a concept of delegates, which relates strongly to the idea of function pointers from C++. Is there a similar functionality in Java? Given that pointers are somewhat absent, what is the best way about this? And to be clear, we're talking first class here.
The Java idiom for function-pointer-like functionality is an an anonymous class implementing an interface, e.g.
Collections.sort(list, new Comparator<MyClass>(){
public int compare(MyClass a, MyClass b)
{
// compare objects
}
});
Update: the above is necessary in Java versions prior to Java 8. Now we have much nicer alternatives, namely lambdas:
list.sort((a, b) -> a.isGreaterThan(b));
and method references:
list.sort(MyClass::isGreaterThan);
You can substitue a function pointer with an interface. Lets say you want to run through a collection and do something with each element.
public interface IFunction {
public void execute(Object o);
}
This is the interface we could pass to some say CollectionUtils2.doFunc(Collection c, IFunction f).
public static void doFunc(Collection c, IFunction f) {
for (Object o : c) {
f.execute(o);
}
}
As an example say we have a collection of numbers and you would like to add 1 to every element.
CollectionUtils2.doFunc(List numbers, new IFunction() {
public void execute(Object o) {
Integer anInt = (Integer) o;
anInt++;
}
});
You can use reflection to do it.
Pass as parameter the object and the method name (as a string) and then invoke the method. For example:
Object methodCaller(Object theObject, String methodName) {
return theObject.getClass().getMethod(methodName).invoke(theObject);
// Catch the exceptions
}
And then use it as in:
String theDescription = methodCaller(object1, "toString");
Class theClass = methodCaller(object2, "getClass");
Of course, check all exceptions and add the needed casts.
No, functions are not first class objects in java. You can do the same thing by implementing a handler class - this is how callbacks are implemented in the Swing etc.
There are however proposals for closures (the official name for what you're talking about) in future versions of java - Javaworld has an interesting article.
This brings to mind Steve Yegge's Execution in the Kingdom of Nouns. It basically states that Java needs an object for every action, and therefore does not have "verb-only" entities like function pointers.
To achieve similar functionality you could use anonymous inner classes.
If you were to define a interface Foo:
interface Foo {
Object myFunc(Object arg);
}
Create a method bar which will receive a 'function pointer' as an argument:
public void bar(Foo foo) {
// .....
Object object = foo.myFunc(argValue);
// .....
}
Finally call the method as follows:
bar(new Foo() {
public Object myFunc(Object arg) {
// Function code.
}
}
Java8 has introduced lambdas and method references. So if your function matches a functional interface (you can create your own) you can use a method reference in this case.
Java provides a set of common functional interfaces. whereas you could do the following:
public class Test {
public void test1(Integer i) {}
public void test2(Integer i) {}
public void consumer(Consumer<Integer> a) {
a.accept(10);
}
public void provideConsumer() {
consumer(this::test1); // method reference
consumer(x -> test2(x)); // lambda
}
}
There is no such thing in Java. You will need to wrap your function into some object and pass the reference to that object in order to pass the reference to the method on that object.
Syntactically, this can be eased to a certain extent by using anonymous classes defined in-place or anonymous classes defined as member variables of the class.
Example:
class MyComponent extends JPanel {
private JButton button;
public MyComponent() {
button = new JButton("click me");
button.addActionListener(buttonAction);
add(button);
}
private ActionListener buttonAction = new ActionListener() {
public void actionPerformed(ActionEvent e) {
// handle the event...
// note how the handler instance can access
// members of the surrounding class
button.setText("you clicked me");
}
}
}
I have implemented callback/delegate support in Java using reflection. Details and working source are available on my website.
How It Works
We have a principle class named Callback with a nested class named WithParms. The API which needs the callback will take a Callback object as a parameter and, if neccessary, create a Callback.WithParms as a method variable. Since a great many of the applications of this object will be recursive, this works very cleanly.
With performance still a high priority to me, I didn't want to be required to create a throwaway object array to hold the parameters for every invocation - after all in a large data structure there could be thousands of elements, and in a message processing scenario we could end up processing thousands of data structures a second.
In order to be threadsafe the parameter array needs to exist uniquely for each invocation of the API method, and for efficiency the same one should be used for every invocation of the callback; I needed a second object which would be cheap to create in order to bind the callback with a parameter array for invocation. But, in some scenarios, the invoker would already have a the parameter array for other reasons. For these two reasons, the parameter array did not belong in the Callback object. Also the choice of invocation (passing the parameters as an array or as individual objects) belongs in the hands of the API using the callback enabling it to use whichever invocation is best suited to it's inner workings.
The WithParms nested class, then, is optional and serves two purposes, it contains the parameter object array needed for the callback invocations, and it provides 10 overloaded invoke() methods (with from 1 to 10 parameters) which load the parameter array and then invoke the callback target.
Check the closures how they have been implemented in the lambdaj library. They actually have a behavior very similar to C# delegates:
http://code.google.com/p/lambdaj/wiki/Closures
Relative to most people here I am new to java but since I haven't seen a similar suggestion I have another alternative to suggest. Im not sure if its a good practice or not, or even suggested before and I just didn't get it. I just like it since I think its self descriptive.
/*Just to merge functions in a common name*/
public class CustomFunction{
public CustomFunction(){}
}
/*Actual functions*/
public class Function1 extends CustomFunction{
public Function1(){}
public void execute(){...something here...}
}
public class Function2 extends CustomFunction{
public Function2(){}
public void execute(){...something here...}
}
.....
/*in Main class*/
CustomFunction functionpointer = null;
then depending on the application, assign
functionpointer = new Function1();
functionpointer = new Function2();
etc.
and call by
functionpointer.execute();

Java Methods - Taking a method AS AN ARGUMENT

I've come across some code that I can't share here but it declares a method WITHIN the paramter list of another method. I didnt even know that was possible. I dont really understand why its doing that. Can someone please explain to me some possible uses that you as a programmer would have for doing that? (Note: Since I can't show the code I dont expect an in-context explanation just generally)
Related:
What's the nearest substitute for a function pointer in Java?
Did the code look something like this?
obj.someMethod(myVar,3,new FooObject() {
public void bar() {
return "baz";
}
});
If so, then the method is not being passed to the other method as an argument, but rather an anonymous inner class is being created, and an instance of that class is being passed as the argument.
In the example above FooObject is an abstract class which doesn't implement the bar() method. Instead of creating a private class that extends FooObject we create an instance of the abstract class and provide the implementation of the abstract method in line with the rest of the code.
You can't create an instance of an abstract class so we have to provide the missing method to create a complete class defintion. As this new class is created on the fly it has no name, hence anonymous. As it's defined inside another class it's an anonymous inner class.
It can be a very handy shortcut, especially for Listener classes, but it can make your code hard to follow if you get carried away and the in line method definitions get too long.
In Java you can't pass methods as parameters. Could it have been passing not a method, but an anonymnous inner class?
This can be useful for passing behaviours between classes. Google "dependency injection" or "Inversion of control" for more information.
Have you ever seen the Functional Java?
It's a very interesting library that allows you programing like you would do in Scala.
I Wrote about this libs. I confess it is better to use in a more flexible syntax (BGGA closures) like Scala.
Using Functional Java with a high-order function like map on a list we have:
final List<Integer> numbers = list(1, 2, 3, 4, 5);
List<Integer> c = numbers.map(new F<Integer, Integer>() {
public Integer f(Integer arg) {
return arg * arg;
}
});
Another useful lib is lambdaj that offers nice ways to play like in Functional (FP) Programming.
Java has a limited syntax compared to FP languages. But you can still take some advantages of FP style, but you must be creative!
using java.lang.reflect.Method
example
public void callMethod(Method aMethod, int value) throws Exception {
aMethod.invoke(this, value);
}
public void print(Integer value) {
System.out.print(value);
}
public void println(Integer value) {
System.out.println(value);
}
public void demo() throws Exception {
Method println = this.getClass().getMethod("println", Integer.class);
Method print = this.getClass().getMethod("print", Integer.class);
callMethod(println, 10);
callMethod(print, 10);
}
The nearest thing to passing a function pointer in Java is passing an anonymous instance of an abstract class or interface. For example, a generic function type can be encoded in an interface like this:
public interface F<A, B> {
public B f(final A a);
}
You can then expect a method in another method's argument list:
public List<B> map(List<A> as, F<A, B> f) {
...
}
And you can call it with an anonymous instance of that interface:
map(myList, new F<Integer, String>() {
public String f(Integer i) {
return String.valueOf(i);
}
});
There's a library called Functional Java that exploits exactly this idea for great benefit glorious language Java.
It's not, per se, legal syntax in Java. Was it perhaps creating a new instance of an anonymous class?
You can also do something like this:
final Predicate somePredicate = new Predicate<Item>()
{
#Override
public boolean apply(Item item)
{
return item.someProperty().equals(something);
}
}
And use it like this:
List<Item> filteredList = filter(list, somePredicate);
I've done stuff like that before. I've also written methods that use a closure to build and return an anonymous implementation of an interface in a similar way:
Predicate isSomeColor(final Color color)
{
return new Predicate<Shape>()
{
#Override
public boolean apply(Shape shape)
{
return shape.getColor().equals(color);
}
}
}
List<Shape> redShapes = filter(shapes, isSomeColor(Color.RED);
All of this is still anonymous inner classes. Nowhere am I actually naming the class itself, I just have a reference to an instance of the class.
this is called reflection. there is a whole library of objects representing stuff like constructors, methods and such.
you can use it, for instance, in order to call a dynamic method that is determined on runtime.
Yes, declaration of a method within the parameter list of another method can be done. You can check out java.lang.reflect.Method
Using reflection, you retrieve a Method object representing the method you wish to pass as a parameter. Then you can call Method to invoke to make a call to that method.
Moreover, you can refer "Functional programming in the Java language" (http ://www.ibm.com/developerworks/java/library/j-fp.html) which can give you inside-out with examples.
The answers above are varying as to whether or not it is even possible. Is it possible through reflection? Is possible through the use of an anonymous inner class? We need to clarify this.
the closest to a function argument is
an instance of a anonymous class with exactly one method.
Runnable a = new Runnable(){
run(){
System.out.println("hello");
}
}
myMethod(a);
not pointer, but still you can write functions inline with some trick.
check my answer on another thread

Function pointers/delegates in Java?

For my Java game server I send the Action ID of the packet which basically tells the server what the packet is for. I want to map each Action ID (an integer) to a function. Is there a way of doing this without using a switch?
What about this one?
HashMap<Integer, Runnable> map = new HashMap<Integer, Runnable>();
map.put(Register.ID, new Runnable() {
public void run() { functionA(); }
});
map.put(NotifyMessage.ID, new Runnable() {
public void run() { functionB(); }
});
// ...
map.get(id).run();
(If you need to pass some arguments, define your own interface with a function having a suitable parameter, and use that instead of Runnable).
Another similar approach could be using Java 8's Suppliers:
Map<Integer, Supplier<T>> suppliers = new HashMap();
suppliers.put(1, () -> methodOne());
suppliers.put(2, () -> methodTwo());
// ...
public T methodOne() { ... }
public T methodTwo() { ... }
// ...
T obj = suppliers.get(id).run();
Java does not have first-class function pointers. In order to achieve similar functionality, you have to define and implement an interface. You can make it easier using anonymous inner classes, but it's still not very pretty. Here's an example:
public interface PacketProcessor
{
public void processPacket(Packet packet);
}
...
PacketProcessor doThing1 = new PacketProcessor()
{
public void processPacket(Packet packet)
{
// do thing 1
}
};
// etc.
// Now doThing1, doThing2 can be used like function pointers for a function taking a
// Packet and returning void
Java doesn't really have function pointers (we got anonymous inner classes instead). There's really nothing wrong with using a switch, though, as long as you're switching on value and not on type. Is there some reason you don't want to use a switch? It seems like you'll have to do a mapping between Action IDs and actions somewhere in your code, so why not keep it simple?
You can use things in java.util.function (For Java 8+) to store a function.
java.util.function docs
You have to go through this list and pick an appropriate function-class to use. I'll be using BiConsumer, which says:
Takes two inputs. Returns no result. Operates through side effects.
import java.util.function.BiConsumer;
import java.util.HashMap;
import java.util.Map;
public void init(){
//<actionId, function<arg1, arg2>>
Map<Integer, BiConsumer<String, String>> actionMap = new HashMap<>();
actionMap.put(123, this::someMethod);
//note (optional): check key first: map.containsKey(someActionId)
//call someMethod("argument1", "argument2")
actionMap.get(123).accept("argument1", "argument2");
}
public void someMethod(String a, String b){
//do something here
}
Have you ever used Swing/AWT? Their Event hierarchy solves a similar problem. The way Java passes functions around is with an interface, for example
public interface ActionHandler {
public void actionPerformed(ActionArgs e);
}
Then, if you want to map integers onto these objects, you could use something like a java.util.HashMap<Integer,ActionHandler> to manage that. The actual implementations can either go in anonymous classes (Java's best approximation of "lambda") or in proper classes somewhere. Here's the anonymous class way:
HashMap<Integer,ActionHandler> handlers;
handlers.put(ACTION_FROB, new ActionHandler() {
public void actionPerformed(ActionArgs e) {
// Do stuff
// Note that any outer variables you intend to close over must be final.
}
});
handlers.get(ACTION_FROB).actionPerformed(foo);
(edit) If you want to be even more abusive, you can initialize the HashMap like so:
HashMap<Integer,String> m = new HashMap<Integer,String>() {{
put(0,"hello");
put(1,"world");
}};
Yeah, but using an interface mean you have to create an interface for each callback which means every function you want to pass it set. Creating a delegate class to handle this gives you (not a true function pointer) but the function to be passed and if you abuse a generic to be the return type, you don't have to cast which cuts the bottleneck down to almost nothing.
The c# delegate (MultiCastDelegate to be correct) gets the info from using method MethodInfo which is the same thing you would need to do for the Delegate class using java.lang.reflect.method. I posted my code for the Delegate(T) class on another form of this site dealing with this extact issue. I make it because (yes) being from C++ I need a better way for passing functions (especially Void) then having to create an interface for on function or more. Now I can choose the function filling in the parameter information for it.
Voila`! Nice and usable with no noticeable lose in speed from JIT or JVM. And if I did having only learning java programming for only a week, any java programmer can do it.
Also, it serves very well when creating a base listener and a base interface to pass in the listener. No more having to write another listener because the name of the function has changed. Creating a delegate class has great advantages as is very useable and passable.
You could interface static methods. This method allows you to specify parameters too. Declare your interface...
public interface RouteHandler {
void handleRequest(HttpExchange t) throws IOException;
}
And your map...
private Map<String, RouteHandler> routes = new HashMap<>();
Then implement static methods that match the interface/params...
public static void notFound(HttpExchange t) throws IOException {
String response = "Not Found";
t.sendResponseHeaders(404, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
You can then add those methods into your map...
routes.put("/foo", CoreRoutes::notFound);
and call them as follows...
RouteHandler handler = routes.get("/foo");
handler.handleRequest(exchange);
You can do this through the use of the chain of responsibility pattern.
It is a pattern that links different objects to together kind of like a linked list. i.e. Each object has a reference to next in the chain. The objects in the chain usually handles one specific behavior. The flow between the objects is very similar to the switch-case statement.
There are some gotchas, such as, it spreads your logic out, an excessively long chain can cause performance problems. But along with these gotchas you have the benefit of increased testability, and stronger cohesion. Also you are not limited to the using enum, byte, int short, and char expressions as the trigger for branching.
Check the closures how they have been implemented in the lambdaj library. They actually have a behavior very similar to C# delegates:
http://code.google.com/p/lambdaj/wiki/Closures

Categories