Skip to content

Conversation

@ilopX
Copy link
Collaborator

@ilopX ilopX commented Jan 25, 2022

Observer pattern

Observer is a behavioral design pattern that lets you define a subscription mechanism to notify
multiple objects about any events that happen to the object they’re observing.

Editor example

In this example, the Observer pattern lets the text editor object notify other service objects about
changes in its state.

More detailed explanation on RefactoringGuru.

Origin source code:

This example rewrite from java example.

Diagram:

image

Client code:

void main() {
  final editor = Editor();
  editor.events
    ..subscribe(
      'open',
      LogOpenListener('log.txt'),
    )
    ..subscribe(
      'save',
      EmailNotificationListener('admin@example.com'),
    );

  try {
    editor.openFile('test.txt');
    editor.saveFile();
  } catch (e) {
    print(e);
  }
}

Output:

Save to log "log.txt": Someone has performed "open" operation with the following file: "test.txt"
Email to "admin@example.com": Someone has performed "save" operation with the following file: "test.txt"

@neochief neochief merged commit a419d88 into RefactoringGuru:master Jan 27, 2022
@ilopX ilopX deleted the add-observer-official-example branch January 27, 2022 12:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants