22:18:13
package demo.desgin_pattern.listener.demo1; /** * @author niecong * @创建时间 2019/8/10 * 事件源持有 一个监听器 并且实现了事件的接口 **/ public class EventSource implements IEvent { boolean button; boolean mouse; private IEventListener mEventListener; //注册监听器 @Override public void setEventListener(IEventListener arg) { mEventListener = arg; } //触发事件 public void mouseEventHappened() { mouse = true; mEventListener.doEvent(this); } @Override public boolean ClickButton() { return button; } @Override public boolean MoveMouse() { // TODO Auto-generated method stub return mouse; } }
1 package demo.desgin_pattern.listener.demo1; 2 3 /** 4 * @author niecong 5 * @创建时间 2019/8/10 6 **/ 7 public class EventSource2 implements IEvent { 8 boolean button; 9 boolean mouse; 10 private IEventListener ml; 11 12 @Override 13 public void setEventListener(IEventListener arg) { 14 ml = arg; 15 } 16 17 @Override 18 public boolean ClickButton() { 19 // TODO Auto-generated method stub 20 return button; 21 } 22 23 @Override 24 public boolean MoveMouse() { 25 // TODO Auto-generated method stub 26 return mouse; 27 } 28 29 // 触发事件 30 public void buttonEventHappened() { 31 button = true; 32 ml.doEvent(this); 33 } 34 35 }
1 package demo.desgin_pattern.listener.demo1; 2 3 /** 4 * @author niecong 5 * @创建时间 2019/8/10 6 **/ 7 public interface IEvent { 8 void setEventListener(IEventListener arg); 9 10 boolean ClickButton(); 11 12 boolean MoveMouse(); 13 14 }
1 package demo.desgin_pattern.listener.demo1; 2 3 /** 4 * @author niecong 5 * @创建时间 2019/8/10 6 * 事件监听器的 方法是事件处理器 7 **/ 8 public interface IEventListener { 9 10 void doEvent(IEvent arg); 11 12 }
package demo.desgin_pattern.listener.demo1; /** * @author niecong * @创建时间 2019/8/10 **/ public class Test { public static void main(String[] args) { // 事件源(被监听的对象) EventSource m1 = new EventSource(); EventSource2 m2 = new EventSource2(); // 监听器 IEventListener mEventListener = new IEventListener() { @Override public void doEvent(IEvent arg) { if (true == arg.ClickButton()) { System.out.println("你点击了按钮"); } else if (true == arg.MoveMouse()) { System.out.println("你移动了鼠标"); } } }; // 注册监听器到事件源 m1.setEventListener(mEventListener); m1.mouseEventHappened(); // 注册监听器到事件源 m2.setEventListener(mEventListener); m2.buttonEventHappened(); } }