###問題描述
實現一個觀察者模式,監聽方法接受一個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); } }