</listener>
三、观察者设计模式设计一个程序
//事件源 public class Student implements Serializable{ private String name; private StudentListener listener; public Student(String name){//注入:通过构造方法 this.name = name; } public String getName() { return name; } public void eat(){ if(listener!=null){ listener.preEat(new StudentEvent(this)); } System.out.println("开始吃"); } public void study(){ if(listener!=null){ listener.preStudy(new StudentEvent(this)); } System.out.println("开始学"); } }
public class StudentEvent { private Object source; public StudentEvent(Object source){ this.source = source; } public Object getSource() {//获取事件源 return source; } }
public interface StudentListener { void preEat(StudentEvent e);//监听吃 void preStudy(StudentEvent e);//监听学 }
public static void main(String[] args) { Student s = new Student("葛付以"); //注册监听器 s.addStudentListener(new StudentListener() { public void preStudy(StudentEvent e) { Student ss = (Student) e.getSource(); System.out.println(ss.getName()+"喝杯奶吧"); } public void preEat(StudentEvent e) { Student ss = (Student) e.getSource(); System.out.println(ss.getName()+"慢慢吃"); } }); s.eat(); s.study(); }
监听器和 利 用观察者设计模式设计一个程序,布布扣,bubuko.com
原文地址:http://blog.csdn.net/ankeyuan/article/details/35597699