###问题描述
实现一个观察者模式,监听方法接受一个Integer参数,而且其打印出来post
###本身实现code
public static void main(String[] args) { EventSource eventSource = new EventSource(); eventSource.register(new Listener()); eventSource.print(1); } interface Print { void print(Integer integer); } static class EventSource implements Print { private Set<Print> listeners = Sets.newCopyOnWriteArraySet(); public void print(Integer integer) { for (Print listener : listeners) { listener.print(integer); } } public void register(Print print) { listeners.add(print); } } static class Listener implements Print { public void print(Integer integer) { System.out.println(integer); } }
###使用JDK实现server
public static void main(String[] args) { EventSource eventSource = new EventSource(); eventSource.addObserver(new Listener()); eventSource.print(1); } static class EventSource extends Observable { public void print(Integer integer) { setChanged(); notifyObservers(integer); } } static class Listener implements Observer { public void update(Observable o, Object arg) { System.out.println(arg); } }
###使用Guavait
public static void main(String[] args) { EventBus eventBus = new EventBus(); eventBus.register(new Listener()); eventBus.post(1); } static class Listener { @Subscribe public void print(Integer integer) { System.out.println(integer); } }