自定义对象如何监听

我们平时总是对sun公司设计好的对象进行监听,有时候我们需要对自己设计的对象进行监听
代码如下:

package com.protelnet.demo;

//观察者设计模式(observer设计模式)
//事件源
class Person {	//设计一个person对象,有两个动作(eat,run方法),这两个动作需要被别人监听
	private PersonListener listenrer;

	public void registerListener(PersonListener listenrer) {
		this.listenrer = listenrer;
	}

	public void eat() {
		if (listenrer != null) {
			Event event = new Event(this);
			this.listenrer.doeat(event);
		}
		System.out.println("eat");
	}

	public void run() {
		if (listenrer != null) {
			Event event = new Event(this);
			this.listenrer.dorun(event);
		}
		System.out.println("run");
	}
}

//事件监听器(封装事件源)
interface PersonListener {
	public void doeat(Event event);

	public void dorun(Event event);
}

//事件对象
class Event {
	private Person person;

	public Event() {

	}

	public Event(Person person) {
		this.person = person;
	}

	public Person getPerson() {
		return person;
	}

	public void setPerson(Person person) {
		this.person = person;
	}
}


以下是调用person象方法,测试监听器是否生效
package com.protelnet.demo;

public class Demo3 {
	public static void main(String[] args) {
		Person person = new Person();
		person.registerListener(new MyListener1()); //注册监听器,监听person对象的eat,run动作
		person.eat();
		person.run();
	}
}

class MyListener1 implements PersonListener {

	public void doeat(Event event) {
		System.out.println(event.getPerson() + "你天天吃,你就知道吃,你猪啊你!");
	}

	public void dorun(Event event) {
		System.out.println(event.getPerson() + "你吃完就跑,有病");
	}
}

你可能感兴趣的:(自定义)