提交 7d490a9c 编写于 作者: N Narendra Pathai

Updated Announcer to use generics

上级 03cdfc3d
......@@ -3,19 +3,20 @@ package com.iluwatar.proxy.example2;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.EventListener;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public class Announcer {
public class Announcer<T extends EventListener> {
private HealthMonitor proxy;
private List<HealthMonitor> listeners = new CopyOnWriteArrayList<>();
private T proxy;
private List<T> listeners = new CopyOnWriteArrayList<>();
public Announcer(Class<HealthMonitor> listenerType) {
public Announcer(Class<T> listenerType) {
proxy = createProxy(listenerType);
}
private HealthMonitor createProxy(Class<HealthMonitor> listenerType) {
private T createProxy(Class<T> listenerType) {
return listenerType.cast(Proxy.newProxyInstance(listenerType.getClassLoader(),
new Class<?>[] {listenerType}, (proxy, method, args) -> {
invokeAll(method, args);
......@@ -24,7 +25,7 @@ public class Announcer {
}
private void invokeAll(Method method, Object[] args) {
for (HealthMonitor listener : listeners) {
for (T listener : listeners) {
try {
method.invoke(listener, args);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
......@@ -33,15 +34,19 @@ public class Announcer {
}
}
public void registerListener(HealthMonitor listener) {
public void registerListener(T listener) {
listeners.add(listener);
}
public HealthMonitor announce() {
public T announce() {
return proxy;
}
public void removeListener(HealthMonitor listener) {
public void removeListener(T listener) {
listeners.remove(listener);
}
public static <T extends EventListener> Announcer<T> to(Class<T> listenerType) {
return new Announcer<>(listenerType);
}
}
......@@ -3,7 +3,7 @@ package com.iluwatar.proxy.example2;
public class EndPoint {
private final String name;
private final Announcer healthMonitors = new Announcer(HealthMonitor.class);
private final Announcer<HealthMonitor> healthMonitors = Announcer.to(HealthMonitor.class);
public EndPoint(String name) {
this.name = name;
......
package com.iluwatar.proxy.example2;
public interface HealthMonitor {
import java.util.EventListener;
public interface HealthMonitor extends EventListener {
void disconnected(EndPoint endPoint);
......
......@@ -16,7 +16,7 @@ public class AnnouncerTest {
private EndPoint endPoint = mock(EndPoint.class);
private HealthMonitor monitor1 = mock(HealthMonitor.class);
private HealthMonitor monitor2 = mock(HealthMonitor.class);
private Announcer announcer = new Announcer(HealthMonitor.class);
private Announcer<HealthMonitor> announcer = Announcer.to(HealthMonitor.class);
@Before
public void setUp() {
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册