-
事件回调操作
-
描述:模拟界面类: 接收用户发起的事件,处理完成后显示结果
-
需求:
-
1.下载完成后需要显示信息
-
2.下载过程中需要显示下载进度
-
a.该干什么事情
-
b.这个事情该怎么做
//把需要上报的事件都定义在接口中
interface INotifyCallBack{
void progress(String file , int progress);
void result(String file);
}
/**
* 负责下载的类
*/
class DownLoad{
private INotifyCallBack cb;//面向接口编程
public DownLoad(INotifyCallBack cb){
this.cb = cb;
}
/**
* 底层执行下载的方法
* @param file
*/
public void start(String file){
int count = 0;
while (count <= 100){
try {
//模拟下载事件
cb.progress(file,count);
Thread.sleep(1000);
count += 20;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
cb.result(file);
}
}
public class GuiTestCase implements INotifyCallBack{
private DownLoad downLoad;
public GuiTestCase(){
this.downLoad = new DownLoad(this);
}
/**
* 下载文件
* @param file
*/
public void downLoadFile(String file){
System.out.println("begin start download file : " + file);
downLoad.start(file);
}
/**
* 显示下载进度的方法
* @param file
* @param progress
*/
public void progress(String file , int progress){
System.out.println("download file : " + file + progress + "%");
}
/**
* 显示文件下载完成了
* @param file
*/
public void result(String file){
System.out.println("download file : " + file + " over.");
}
public static void main(String[] args) {
GuiTestCase gui = new GuiTestCase();
gui.downLoadFile("视频文件");
}
}
run。。。。
界面类依赖下载类:上层依赖下层 合理
下载类定义回调的接口,从而实现面向接口编程