Facebook Pixel

Exercise: Observer

This exercise puts the Observer pattern into code.

Scenario

A Publisher manages a registry of Subscriber objects. Each subscriber holds a name and an update(msg) method that returns "<name> got <msg>". When the publisher receives a message, it calls update on each subscriber in subscription order and collects the results. Duplicate subscriptions are silently ignored; the original position is preserved.

Commands

CommandBehaviorOutput
["subscribe", name]Register the subscriber; ignore if already subscribed(none)
["unsubscribe", name]Remove the subscriber if present; do nothing otherwise(none)
["publish", msg]Notify every current subscriber in subscription orderone line per subscriber: "<name> got <msg>"; if no subscribers: "No subscribers"

A single publish command can emit multiple output lines — one per active subscriber.

Example
Input
6
subscribe Alice
subscribe Bob
publish hello
unsubscribe Bob
subscribe Alice
publish bye
Output
Alice got hello
Bob got hello
Alice got bye
Explanation

Alice and Bob subscribe, so the first publish notifies both in subscription order, producing two lines. Bob then unsubscribes. The second subscribe Alice is a duplicate and is silently ignored — Alice keeps her original position. The second publish notifies only Alice. Note that subscribe and unsubscribe produce no output; only publish prints lines.

Your task

Implement the skeleton in the editor below so the commands produce the output described above.

Invest in Yourself
Your new job is waiting. 83% of people that complete the program get a job offer. Unlock unlimited access to all content and features.
Go Pro