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