接口運(yùn)用場(chǎng)景妻献、接口回調(diào)
接口有什么用?有好多好多案例蛛株,比如你忙的時(shí)候,快遞來(lái)了育拨,你沒(méi)時(shí)間去取谨履,那你叫同學(xué)去幫你取,取了之后打個(gè)電話告訴你熬丧。笋粟。。等等之類的運(yùn)用很多析蝴。
案例
使用場(chǎng)景:你叫舍友給你收一下衣服害捕,收完之后給你說(shuō)一聲;
/**
* 建模: CallBack(收完衣服的結(jié)果) Sheyou(舍友) You(你)
* 接口回調(diào)
*/
public class Demo{
public static void main(String[] args) {
You you = new You();//創(chuàng)建一個(gè)你
Sheyou leifeng = new Sheyou("雷鋒"); //創(chuàng)建一個(gè)雷鋒同學(xué)
you.requestShouyifu(leifeng);//委托雷鋒舍友收衣服
}
}
interface CallBack {
void result(String msg);
}
class You implements CallBack {
/**
* 請(qǐng)求舍友幫你收衣服(客氣點(diǎn))
*
* @param sheyou
*/
public void requestShouyifu(Sheyou sheyou) {
System.out.println(sheyou.name + "請(qǐng)幫我收一下衣服闷畸,要下雨了");
sheyou.shouyifu(this);//叫他去做的同時(shí)注冊(cè)監(jiān)聽(tīng)他有沒(méi)有把這件事做好
}
@Override
public void result(String msg) {
System.out.println("我知道" + msg);
}
}
class Sheyou {
String name;
public Sheyou(String name) {
this.name = name;
}
//收衣服
public void shouyifu(CallBack callBack) {
System.out.println(this.name + "收衣服中...");
callBack.result("衣服已經(jīng)收好了尝盼。" + "\t" + this.name + "收的.");
}
}