一个回调问题的例子

个人理解就是A函数调用B函数后,B再通过调用A的接收方法将结果返回给A。

场景应用:

假设Tom去书店买书,由于书店的书比较多,店员不能立即找到,而Tom还有其他事要做,所以Tom就留下联系方式给了店员,让店员找到书后立即通知Tom。

其中“店员找到书后立即通知Tom”就是属于回调。

Tom: I want to buy a book. When you find it,call me.
Tom walked out....
Jack: I want to buy a book. When you find it,call me.
BookStore: checking Tom's books...
Jack walked out....
BookStore: checking Jack's books...
BookStore: I find the book,I will infomation--->Tom
BookStore: I find the book,I will infomation--->Jack
Jack: I got the infomation "BookStore: I hava your book." from the bookstore.
Tom: I got the infomation "BookStore: I hava your book." from the bookstore.
Tom: I bought a book.
Jack: I bought a book.

附上源码:

package CallBack;

public interface CallBack {
	public void callBack(String info);
}
package CallBack;

public class Customer implements CallBack{
	
	private BookStore bookStore;
	private String custName;
	
	public Customer(String custName,BookStore bookStore) {
		this.bookStore = bookStore;
		this.custName = custName;
	}
	
	public String getCustName() {
		return custName;
	}
	
	public void buyBook() {
		System.out.println(custName +": I want to buy a book. When you find it,call me.");
		
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					checkBook();
					Thread.sleep(500);
					
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
		}
				).start();
		System.out.println(custName+" walked out....");
	}
	
	public void checkBook() {
		bookStore.checkBook(this);
	}

	@Override
	public void callBack(String info) {
		System.out.println(custName +": I got the infomation \""+info+"\" from the bookstore.");
		System.out.println(custName +": I bought a book.");
	}

}
package CallBack;

public class BookStore {
	
	public void checkBook(Customer customer) {
		System.out.println("BookStore: checking "+ customer.getCustName() +"\'s books...");
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					Thread.sleep(1000);
					info(customer);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
		}
				).start();		
	}
	public void info(Customer customer) {
		System.out.println("BookStore: I find the book,I will infomation--->"+ customer.getCustName());
		customer.callBack("BookStore: I hava your book.");
	}
}
package CallBack;

public class CallbackTest {
	public static void main(String[] args) {
		BookStore bookStore = new BookStore();
		Customer customer1 = new Customer("Tom",bookStore);
		Customer customer2 = new Customer("Jack",bookStore);
		customer1.buyBook();
		customer2.buyBook();
	}
}

以上纯属个人见解,欢迎讨论~

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值