监听器就是在事件之前再加上一段代码,为了降低耦合,写成另一个类*(监听类),并把当前的对象传递给这个类,为了再降低监听类的参数的耦合,需要把传入的参数再封装一下,封装成even。
运行程序的main代码
package com.Demo;
public class Demo {
public static void main(String[] args) {
Person p = new Person();
p.registerListener(new PersonListener() {
@Override
public void doRun(Even e) {
System.out.println(e.getP().getClass() + " is running");
}
@Override
public void doEat(Even e) {
System.out.println(e.getP().getClass() + " is eatting");
}
});
p.run();
p.eat();
}
}
运行结果:
class com.Demo.Person is running
run........
class com.Demo.Person is eatting
eat........
package com.Demo;
class Person {
private PersonListener listener;
public void run() {
if (listener != null) {
listener.doRun(new Even(this));
}
System.out.println("run........");
}
public void eat() {
if (listener != null) {
listener.doEat(new Even(this));
}
System.out.println("eat........");
}
// 注册监听器
public void registerListener(PersonListener listener) {
this.listener = listener;
}
}
监听器接口
package com.Demo;
interface PersonListener {
public void doRun(Even e);
public void doEat(Even e);
}
参数even:
package com.Demo;
class Even {
private Person p;
public Even(Person p) {
this.p = p;
}
public Person getP() {
return p;
}
public void setP(Person p) {
this.p = p;
}
}