监听者模式

事件源触发,被pulish到监听者,实现监听功能,本文用反射的方法进行publish.

事件源

public class MyEvent extends EventObject
{
private static final long serialVersionUID = 1L;
private String name;
private int age;

public MyEvent(Object source, String name, int age)
{
super(source);
this.name = name;
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}
}

2监听接口:

public interface MyLisetener extends EventListener
{
public void onMyEventPublish(MyEvent event);

}

3.监听者实现.

public class ListenImpl1 implements MyLisetener
{
@Override
public void onMyEventPublish(MyEvent event)
{
System.out.println("source......"+ event.getSource());
System.out.println("this is ListenImpl1....." +event.getName());
System.out.println("this is ListenImpl1......" +event.getAge());
}

}

public class ListenImpl2 implements MyLisetener
{
@Override
public void onMyEventPublish(MyEvent event)
{
System.out.println("source......"+ event.getSource());
System.out.println("this is ListenImpl2......" +event.getName());
System.out.println("this is ListenImpl2....." +event.getAge());
}

}

4.测试监听者模式

public class TestMyEvent
{
public static void main(String[] args) throws ClassNotFoundException,Exception
{

//Class clazz2 = Class.forName("com.test.lisener.ListenImpl2");
List<MyLisetener> lisenList = new ArrayList<MyLisetener>();
lisenList.add(new ListenImpl1());
lisenList.add(new ListenImpl2());
MyEvent event = new MyEvent("refresh", "Micheal", 23);
publish(lisenList, event);
}

public static void publish(List<MyLisetener> lisenList,MyEvent event) throws Exception
{
Class clazz = Class.forName("com.test.lisener.MyLisetener");
Method method1 = clazz.getDeclaredMethods()[0];
for (MyLisetener obj: lisenList)
{
method1.invoke(obj, new Object[]{event});
}
}

}

输出为:

source......refresh
this is ListenImpl1.....Micheal
this is ListenImpl1......23
source......refresh
this is ListenImpl2......Micheal
this is ListenImpl2.....23

原文地址:https://www.cnblogs.com/daxiong225/p/8821877.html