觀察者 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
}
}