In software architecture, the Publisher-subscriber pattern is centered around networks, while the Observer pattern focuses on individual objects and events.
These patterns are utilized at various levels within software systems.
Essentially, the Observer pattern operates within the confines of an application or single process, whereas Publish-Subscribe facilitates communication across applications by exchanging messages between different processes.
When discussing the Observer pattern, only two classes are typically required:
- Publisher or Subject: The source of events that listeners want to hear from.
- Subscriber or Observer: Those who wish to receive events generated by the Publisher or Subject.
Here's an example showcasing abstractions for the Observer and Publisher (Subject):
interface IMyObserver
{
update: (myMessage: string) => void;
}
interface IMySubject
{
registerObserver: (o: IMyObserver) => void;
removeObserver: (o: IMyObserver) => void;
notifyObservers: () => void;
}
Below is a concrete implementation of the IMyObserver
:
class MyObserver implements IMyObserver
{
_mySubject: MySubject
_myMessage: string | undefined
constructor(mySubject: MySubject)
{
this._mySubject = mySubject;
this._mySubject.registerObserver(this);
}
update(myMessage: string) : void {
this._myMessage = myMessage;
console.log(`The Observer has received this message: ${this._myMessage}`);
}
}
This is a specific implementation of IMySubject
:
class MySubject implements IMySubject
{
_observers: IMyObserver[] = []
_myMessage?: string
_messageFromObserver?: string
notifyObservers()
{
this._observers.forEach(obs => obs.update(this._myMessage ?? ''))
}
registerObserver(o: IMyObserver):void {
this._observers.push(o)
}
removeObserver(o: IMyObserver) {
const index = this._observers.indexOf(o);
if(index !== -1) {
this._observers.splice(index, 1);
}
}
myMessageChanged() {
this.notifyObservers()
};
setMessage(message: string)
{
this._myMessage = message;
this.myMessageChanged();
}
}
To execute the above code, follow these steps:
const mySubject = new MySubject();
const myObserver = new MyObserver(mySubject);
// Sending a message from the subject
mySubject.setMessage("Hello World!");