java callback termination sticker

java callback termination sticker

                                                                                                        - I've never really trusted my memory, so I write them all down 

   

    Writing programs does not understand the ugly point of callbacks. There is really no entry. Event-driven are basically callback implementations, such as button clicks in Android and button clicks in Swing. There are really too many places for callbacks to be used. Down. But the callback is just that round, and it is confusing for a while. The following two examples will surely make you understand callbacks.

In the first example, we take the android click button as an example

    Button.class

 

/**
 * This is a button
 * @author albert
 *
 */
public class Button {
        //click button
	public void click(ClickListener listenner){
		listenner.onClick();
	}
}

 Click event interface, used by Button's click event

/**
 * Simulate event processing, and give the implementer the specific algorithm after the click
 * @author albert
 *
 */
interface ClickListener{
	public void onClick();
}

 The following is the specific processing of clicking a button on an Activity

 

 

/**
 * Simulate the interface in android (you can add Button, etc.)
 * @author albert
 *
 */
public class Activity {
	public static void main(String[] args) {
		Button btn = new Button();
		btn.click(new ClickListener() {
			@Override
			public void onClick() {
				System.out.println("The algorithm to be executed after clicking is implemented here");
			}
		});
	}
}

 After running the Activity, the console prints a piece of text. I don't know if everyone understands this, but this is the actual operation process, let's abstract it.

 

 

public class A {
	public void func(CallBack callBack){
		callBack.call();
	}
}
/**Callback interface*/
interface CallBack{
	public void call();
}

 

 

Concrete implementation class B

public class B {
	public static void main(String[] args) {
		A a = new A();
		a.func(new CallBack() {
			@Override
			public void call() {
				System.out.println("The algorithm to be executed after clicking is implemented here");
			}
		});
	}
}

 

 

The above two examples should be well understood, and then class B can be improved

 

public class B implements CallBack{
	public static void main(String[] args) {
		B b = new B();
		A a = new A();
		a.func(b);
	}

	@Override
	public void call() {
		System.out.println("Let B implement the callback interface");
	}
}

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326272371&siteId=291194637