Java callback mechanism (Boss and employee example)

Source: Internet
Author: User

On the internet to see an old brother wrote a callback small case, feeling write really good, concise.

Learn and share my understanding.

Nonsense not to say, directly on the code.

Resolve time-consuming operational issues when calling asynchronously (requesting network hard disk resources, etc.). )

In Android, Button.setonclicklister (New Onclicklister ()

{

asynchronous invocation, Lister monitoring without waiting

}



/** * A programmer wrote a program A, which reserved a callback function interface, and encapsulated the program, * programmer B let a call its own program B in a method, * So, he through the interface in a callback to the method in B, * * A is equivalent to the Employee interface (office address) old The board changed the stubble and the office address did not change. * method in B: Leader:excute () or Boss:excute (), which is the callback function * @author asus-000000 **/ Public classMain { Public Static voidMain (string[] args) {boss Boss=NewBoss (); Leader Leader=NewLeader (); Employee Employee=NewEmployee (); Employee.setcallback (leader); Employee.dosoming (); Employee.setcallback (boss); Employee.dosoming (); }}

 Public class Boss implements callback{    @Override    publicvoid  Excute () {        //  TODO auto-generated method stub        System.  out. println ("Boss Get your message! " );    }}

 Public Interface CallBack {    publicvoid  excute ();}

 Public class Leader implements callback{    @Override    publicvoid  Excute () {        //  TODO auto-generated method stub        System.  out. println ("Leader Get your message good job: " );    }}

 Public classEmployee {PrivateCallBack CallBack; Public voidSetcallback (CallBack CallBack) { This. callback=CallBack;} Public voiddosoming () {System. out. println ("Employee is work ..."); System. out. println (" work was done"); Callback.excute ();}}

Java callback mechanism (Boss and employee example)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.