解決的問題:
現實處理邏輯中,我們經常遇到這種邏輯,當msg="放假了"的時候,Teacher,Student,Parent分別做出相應的動作(doMyEvent)
一般這樣寫:
if( msg.equalsIgnoreCase("放假了")){
teacher.doMyEvent();
student.doMyEvent();
parent.doMyEvent();
}
每次有消息發送過來,都要寫這幾行,顯然太麻煩,我們採用監視器,註冊一次,就可對消息進行分發
1. 定義接口
public interface MyListener {
public void doMyEvent();
}
2.定義Teacher/Student/Parent的實現類
public class TeacherListener implements MyListener {
@Override
public void doMyEvent() {
// TODO Auto-generated method stub
System.out.println("老師舒心了");
}
}
public class StudentListener implements MyListener {
@Override
public void doMyEvent() {
// TODO Auto-generated method stub
System.out.println("學生開心了");
}
}
public class ParentListener implements MyListener {
@Override
public void doMyEvent() {
// TODO Auto-generated method stub
System.out.println("父母鬧心了");
}
}
3.定義消息分發器
public class MyNotice {
//監聽器容器
private List<MyListener> listener = new ArrayList<MyListener>();
//給事件綁定監聽器
public void addMyListener(MyListener ren) {
listener.add(ren);
}
//事件觸發器
public void tellMe(String msg) {
if(msg.equalsIgnoreCase("放假了")) {
Iterator<MyListener> iterator = listener.iterator();
while(iterator.hasNext()) {
MyListener ren = iterator.next();
ren.doMyEvent();
}
}
}
}
4.定義main函數
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyNotice notice = new MyNotice();
notice.addMyListener(new TeacherListener());
notice.addMyListener(new StudentListener());
notice.addMyListener(new ParentListener());
String msg = "放假了";
notice.tellMe(msg);
}
}