Chenxu.Fu15 1509284
-
The program requires Node.js and NPM(or Yarn) as packager manager installed.
-
From root directory, run
cd original
andnpm install
(oryarn install
) -
From root directory, run
cd observer
andnpm install
(oryarn install
)
-
From root directory, run
cd original
andnpm start
(oryarn start
) -
Server will start on port 6395(default), and browser will open automatically on
http://localhost:8080
-
From root directory, run
cd observer
andnpm start
(oryarn start
) -
Server will start on port 6396(default), and browser will open automatically on
http://localhost:8081
Observer Design Pattern decouples different types of objects in terms of Observer and Subject(Observable), defining a one-to-many dependencies, and when the subject changes, all its observers will be updated automatically.
As real world examples, user can subscribe a newsletter, a podcast or chatroom. When new content is added, instead of users actively polling for changes(interval refresh), the users can be notified by the server directly.
The detailed webpage example makes use of WebSocket to implement the Observer Design Pattern. In this example, server and client act as both Observer and Subject. When user publishes a new message, The server observes the event emitted from client, and then dispatch the event to other clients. The other clients will observe for events emitted from server and be updated automatically.
The code abstracts the basic principle of Observer Design Pattern, the Subject(newsletter) can subscribe and unsubscribe multiple Observers(users) by updating the subscription list. When the Subject dispatch an event, it will loop through the subscription list and notify them.