观察者 Java

观察者模式允许类的用户订阅当该类处理数据等时发生的事件,并在这些事件发生时得到通知。在下面的示例中,我们创建了一个处理类和一个观察者类,它将在处理短语时得到通知 - 如果它找到长度超过 5 个字母的单词。

LongWordsObserver 接口定义了观察者。实现此接口以将观察者注册到事件。

// an observe that can be registered and receive notifications
public interface LongWordsObserver {
    void notify(WordEvent event);
}

WordEvent 类是一旦发生某些事件就会被发送到观察者类的事件(在这种情况下,发现了长字)

// An event class which contains the long word that was found
public class WordEvent {

    private String word;

    public WordEvent(String word) {
        this.word = word;
    }

    public String getWord() {
        return word;
    }
}

PhraseProcessor 类是处理给定短语的类。它允许使用 addObserver 方法注册观察者。一旦找到长单词,将使用 WordEvent 类的实例调用这些观察者。

import java.util.ArrayList;
import java.util.List;

public class PhraseProcessor {

    // the list of observers
    private List<LongWordsObserver> observers = new ArrayList<>();

    // register an observer
    public void addObserver(LongWordsObserver observer) {
        observers.add(observer);
    }

    // inform all the observers that a long word was found
    private void informObservers(String word) {
        observers.forEach(o -> o.notify(new WordEvent(word)));
    }

    // the main method - process a phrase and look for long words. If such are found,
    // notify all the observers
    public void process(String phrase) {
        for (String word : phrase.split(" ")) {
            if (word.length() > 5) {
                informObservers(word);
            }
        }
    }
}

LongWordsExample 类显示如何注册观察者,调用 process 方法并在找到长单词时接收警报。

import java.util.ArrayList;
import java.util.List;

public class LongWordsExample {

    public static void main(String[] args) {

        // create a list of words to be filled when long words were found
        List<String> longWords = new ArrayList<>();

        // create the PhraseProcessor class
        PhraseProcessor processor = new PhraseProcessor();

        // register an observer and specify what it should do when it receives events,
        // namely to append long words in the longwords list
        processor.addObserver(event -> longWords.add(event.getWord()));

        // call the process method 
        processor.process("Lorem ipsum dolor sit amet, consectetuer adipiscing elit");

        // show the list of long words after the processing is done
        System.out.println(String.join(", ", longWords));
        // consectetuer, adipiscing
    }
}