The Observer Pattern is a behavioral design pattern that defines a one-to-many
dependency between objects, ensuring that when one object changes state, all its
dependents are notified and updated automatically. This pattern is particularly
useful for implementing event-driven systems and maintaining consistency across
related objects.
typeObserver={update(subject: Subject):void;};classSubject{getcounter() {return0;}privatereadonlyobservers: Observer[]=[];attach(observer: Observer):void{this.observers.push(observer);}detach(observer: Observer):void{constindex=this.observers.indexOf(observer);if(index>-1){this.observers.splice(index,1);}}notify():void{for(constobserverofthis.observers){observer.update(this);}}}classConcreteSubjectextendsSubject{// Concrete subject can have its own state or methods
// that, when changed, trigger notifications
someState="";setState(newState: string):void{this.someState=newState;this.notify();// Notify observers when state changes
}}classConcreteObserverimplementsObserver{update(subject: Subject):void{if(subjectinstanceofConcreteSubject){// Type guard
console.log(`Updated. Subject's state: ${subject.someState}`);}else{console.log("Updated");}}}// List and Iterator implementations (from previous examples)
// ... (Include the List and Iterator implementations from the previous response here)
constexample={run():void{constsubject=newConcreteSubject();constobserver=newConcreteObserver();subject.attach(observer);subject.setState("New State!");// Example of state change and notification
constobserver2=newConcreteObserver();subject.attach(observer2);subject.setState("Another State!");// Example with multiple observers
subject.detach(observer);// Detach an observer
subject.setState("Yet Another State!");// Observer should not be notified
}};example.run();