- import java.util.*;
- public class TestGirl {
- public static void main(String[] args) {
- Girl g = new Girl("秋香");
- Boy1 boy1 = new Boy1("zhaojun");
- g.addEmotionListener(boy1);
- g.fire();
- g.removeEmotionListener(boy1);
- Boy2 boy2 = new Boy2("ankun");
- g.addEmotionListener(boy2);
- g.fire();
- g.removeEmotionListener(boy2);
- }
- }
- /*
- * 事件: 封装事件源
- */
- class EmotionEvent extends EventObject{
- public EmotionEvent(Object source){
- super(source);
- }
- }
- /*
- * 监听器: 处理事件
- */
- interface EmotionListener extends EventListener{
- void whatCanIdoWhenGirlSad(EmotionEvent event);
- void whatCanIdoWhenGirlHappy(EmotionEvent event);
- }
- /*
- * 事件源:产生事件
- */
- class Girl{
- private String name;
- private EmotionListener listener;
- public Girl(String name){
- this.name = name;
- }
- public String getName(){
- return this.name;
- }
- public void addEmotionListener(EmotionListener listener){
- System.out.println(name +" said: 找到一个男朋友!");
- this.listener = listener;
- }
- public void removeEmotionListener(EmotionListener listener){
- System.out.println(name +" said: 离开你我怎么活呀!");
- listener = null;
- }
- public void fire(){
- for(int i=1; i<4; i++){
- System.out.println("Day" + i + ":");
- if(i%2 == 0){
- System.out.println(name + " said: " + "今天我不太开心!");
- EmotionEvent event = new EmotionEvent(this);
- listener.whatCanIdoWhenGirlSad(event);
- }else{
- System.out.println(name + " said: " + "今天我好开心!");
- EmotionEvent e = new EmotionEvent(this);
- listener.whatCanIdoWhenGirlHappy(e);
- }
- }
- }
- }
- class Boy1 implements EmotionListener{
- private String name;
- public Boy1(String name){
- this.name = name;
- }
- @Override
- public void whatCanIdoWhenGirlHappy(EmotionEvent event) {
- Object obj = event.getSource();
- Girl g = (Girl)obj;
- System.out.println(name + " said to "+g.getName() +": 你开心我也挺开心的!");
- }
- @Override
- public void whatCanIdoWhenGirlSad(EmotionEvent event) {
- Girl g = (Girl)event.getSource();
- System.out.println(name + " said to "+g.getName()+ ": 你不开心我挺不愉快的!!");
- }
- }
- class Boy2 implements EmotionListener{
- private String name;
- public Boy2(String name){
- this.name = name;
- }
- @Override
- public void whatCanIdoWhenGirlHappy(EmotionEvent event) {
- Girl g = (Girl)event.getSource();
- System.out.println(name + " said to "+ g.getName() +": 你开心我挺不开心的!");
- }
- @Override
- public void whatCanIdoWhenGirlSad(EmotionEvent event) {
- Girl g = (Girl)event.getSource();
- System.out.println(name + " said to "+ g.getName() +": 你不开心我挺愉快的!!");
- }
- }
EventListener,监听注册
最新推荐文章于 2023-01-05 20:32:16 发布