Search code examples
javadesign-patternsmethodscallbackmethod-parameters

Design Patterns: Callback as a method parameter


I was wondering if defining a callback for a operation in a method parameter is worse than defining it in the object and setting via setters, concerning about design patterns.

I'm not sure if exists a design pattern regarding callback creations.

For example, let's say that there is some class A, and I want to execute a methodM with some callback.

public class A {
    public interface Callback {
        void onEvent();
    }
    public static methodM(...) {
        // ...
    }
}

May I do this:

public static void methodM(Callback c) {
    c.onEvent();
}
// ...
A.method(this); // The class that calls the method is the callback!

Instead of:

public static void setCallback(Callback callback) {
    this.callback = callback;
}
public static void methodM() {
    this.callback.onEvent();
}
// ...
A.setCallback(this); // The class that calls the method is the callback!
A.method(); 

Note that the fact of the method be static is just to easy the scenario understanding.

So, can I use the first approach as a valid design?

The reason about using the first scenario is to avoid memory leaks as to easy the definition of simple callbacks for multiple execution, since I would have to control a list of callbacks using either lists, observers, etc.


Solution

  • I don't think there is a "Callback pattern", it's too generic.

    Yet, many Design patterns use callback, like Observer pattern or Visitor pattern

    It will depends of the global architecture of your program

    That piece of code

    public static void methodM(Callback c) {
        c.onEvent();
    }
    // ...
    A.method(this); // The class that calls the method is the callback!
    

    does not bother me, it's not something forbidden if presented like this