监视器其实就是当某个事件完成后,自动监控到该情况然后去执行你想要的操作。
举个例子吧,我们在浏览器里在下载东西,然后你点击了后台下载,当下载结束后,浏览器会弹窗告诉你下载完成了,我们就写段简单的代码来抽象的实现这个小需求。
首先写一个IListener接口,IListener.java:
package listenertest3;
public interface IListener {
public void afterDownLoad(DownLoadEvent event);
}
然后是实现了IListener接口的DownLoadListener.java:
package listenertest3;
public class DownLoadListener implements IListener {
@Override
public void afterDownLoad(DownLoadEvent event) {
System.out.println(event.getFileName() + " download finished");
}
}
写一个下载事件类DownLoadEvent.java,里边有文件名称以及是否下载完成两个属性:
package listenertest3;
public class DownLoadEvent {
private String fileName;
private boolean isFinish = false;
public DownLoadEvent(String fileName) {
this.fileName = fileName;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public boolean isFinish() {
return isFinish;
}
public void setFinish(boolean isFinish) {
this.isFinish = isFinish;
}
}
接下来是事件发生类DownLoadFile.java,在其中的download方法中首先打印出start download,然后暂停1000ms代表下载,之后下载完成,将下载事件中的下载是否完成属性设成true,然后就会执行listerner中的afterDownLoad方法:
package listenertest3;
public class DownLoadFile {
private IListener listener;
public IListener getListener() {
return listener;
}
public void setListener(IListener listener) {
this.listener = listener;
}
public void download() throws InterruptedException {
DownLoadEvent event = new DownLoadEvent("No Man Land");
System.out.println("start download");
Thread.sleep(1000);
event.setFinish(true);
listener.afterDownLoad(event);
}
}
最后是main方法:
package listenertest3;
public class MainTest {
public static void main(String[] args) throws InterruptedException {
DownLoadFile downloadFile = new DownLoadFile();
downloadFile.setListener(new DownLoadListener());
downloadFile.download();
}
}
运行结果如下: