|
| 1 | +package com.brianway.learning.java8.effective.tech; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +/** |
| 7 | + * 观察者模式 |
| 8 | + */ |
| 9 | +public class ObserverMain { |
| 10 | + |
| 11 | + public static void main(String[] args) { |
| 12 | + //old school |
| 13 | + Subject f = new Feed(); |
| 14 | + f.registerObserver(new NYTimes()); |
| 15 | + f.registerObserver(new Guardian()); |
| 16 | + f.registerObserver(new LeMonde()); |
| 17 | + f.notifyObservers("The queen said her favourite book is Java 8 in Action!"); |
| 18 | + |
| 19 | + // with lambdas |
| 20 | + Feed feedLambda = new Feed(); |
| 21 | + |
| 22 | + feedLambda.registerObserver((String tweet) -> { |
| 23 | + if (tweet != null && tweet.contains("money")) { |
| 24 | + System.out.println("Breaking news in NY! " + tweet); |
| 25 | + } |
| 26 | + }); |
| 27 | + feedLambda.registerObserver((String tweet) -> { |
| 28 | + if (tweet != null && tweet.contains("queen")) { |
| 29 | + System.out.println("Yet another news in London... " + tweet); |
| 30 | + } |
| 31 | + }); |
| 32 | + |
| 33 | + feedLambda.notifyObservers("Money money money, give me money!"); |
| 34 | + |
| 35 | + } |
| 36 | + |
| 37 | + interface Observer { |
| 38 | + void inform(String tweet); |
| 39 | + } |
| 40 | + |
| 41 | + interface Subject { |
| 42 | + void registerObserver(Observer o); |
| 43 | + |
| 44 | + void notifyObservers(String tweet); |
| 45 | + } |
| 46 | + |
| 47 | + static private class NYTimes implements Observer { |
| 48 | + @Override |
| 49 | + public void inform(String tweet) { |
| 50 | + if (tweet != null && tweet.contains("money")) { |
| 51 | + System.out.println("Breaking news in NY!" + tweet); |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + static private class Guardian implements Observer { |
| 57 | + @Override |
| 58 | + public void inform(String tweet) { |
| 59 | + if (tweet != null && tweet.contains("queen")) { |
| 60 | + System.out.println("Yet another news in London... " + tweet); |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + static private class LeMonde implements Observer { |
| 66 | + @Override |
| 67 | + public void inform(String tweet) { |
| 68 | + if (tweet != null && tweet.contains("wine")) { |
| 69 | + System.out.println("Today cheese, wine and news! " + tweet); |
| 70 | + } |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + static private class Feed implements Subject { |
| 75 | + private final List<Observer> observers = new ArrayList<>(); |
| 76 | + |
| 77 | + public void registerObserver(Observer o) { |
| 78 | + this.observers.add(o); |
| 79 | + } |
| 80 | + |
| 81 | + public void notifyObservers(String tweet) { |
| 82 | + observers.forEach(o -> o.inform(tweet)); |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | +} |
0 commit comments