イベント・リスナーの原理-イベント・オブジェクト、イベント・リスナー、イベント・ソース
6679 ワード
package cn.my.demo;
//
public class Demo2 {
public static void main(String[] args) {
Person p=new Person(1001," ");
p.refisterListener(new PersonListener() {
public void dorun(Event e) {
Person p=e.getSource();
System.out.println("Who is in front of people to have a meal, that is "+p.getName());
}
public void doeat(Event e) {
Person p=e.getSource();
System.out.println("Who in the previous run, that is "+p.getName());
}
});
p.eat();
p.run();
}
}
//
class Person{
private Integer id ;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Person(Integer id ,String name)
{
this.id=id;
this.name=name;
}
//
private PersonListener listener;
public void eat(){
if(listener!=null){
listener.doeat(new Event(this));
}
System.out.println("this is eat!");
}
public void run(){
if(listener!=null){
listener.dorun(new Event(this));
}
System.out.println("this is run!");
}
public void refisterListener(PersonListener listener){
this.listener=listener;
}
}
//
interface PersonListener{
public void doeat(Event e);
public void dorun(Event e);
}
//
class Event{
//
private Person source;
public Person getSource() {
return source;
}
public Event(Person source) {
super();
this.source = source;
}
public Event() {
super();
}
public void setSource(Person source) {
this.source = source;
}
}