Skip to content

Instantly share code, notes, and snippets.

@wendyltan
Last active November 23, 2020 16:15
Show Gist options
  • Save wendyltan/45256a443394607e214c7961008d2168 to your computer and use it in GitHub Desktop.
Save wendyltan/45256a443394607e214c7961008d2168 to your computer and use it in GitHub Desktop.
Java-Callback

How to understand callback mechanism?

We can always see many callback functions in Java,but how does that actually work?

We know that there is five step to simulate a callback process:

  • Class A implements Callback interface. /The interface has abstract function operate()/
  • Class A has a member Class B's instance /b/
  • Class B has a method using callback /Callback instance as parameter/doSth(Callback callback)/
  • A's instance a invoked B's instance b's method /b.doSth(this),use this because a is a concrete callback/
  • b invoke a's method,for example, /a.operate() in b.doSth(Callback callback)/

After the above process,it just seems the b finish the job and return result for a!This is what we call "Callback" :

Pass the job to server,when the job done,the server call the client and return feedback!

The following will be some codes example:

/**
Callback.java
**/

//Whoever implement this can drink the beverage
public interface Callback(){
    public void drinkBeverage(String beverage);
}
/**
Me.java
**/

public class Me implements Callback{

    Roommate roommate;

    public Me(Roommate roommate){
        this.roommate = roommate;
    }

    public void getBeverageAndDrink(){
        //I'm too lazy to buy a beverage so I'm gonna ask my roommate.
        roommate.buyBeverage(this);
    }


    @Override
    public void drinkBeverage(String beverage){
        //when my roommate call me,I can drink the beverage...
        sout("I drink "+ beverage+" !");
    }
}
/**
Roommate.java
**/

public class Roommate{
    
    public void buyBeverage(Callback callback){
        //roommate got the beverage somewhere.we don't care.
        String beverage = "Vita-lemonTea";

        //call me to drink beverage,the beverage is bought.
        callback.drinkBeverage(beverage);

    }

}
/**
Test.java
**/

public class Test{
    public static void main(String[] args){

        Roommate huangyep = new Roommate();
        Me wendy = new Me(huangyep);
        wendy.getBeverageAndDrink();

    }

}

This example is the simplest to explain this concept.Of course there is more complex examples,If I think of any I'll add it in.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment