abstract class Persen { abstract update ( ) ; protected subject : Subject ; } type state = 'await' | 'publish' ; class Subject { private _state : state = 'await' ; subs : Persen [ ] = [ ] ; lock = false ; set state ( state ) { if ( this . lock || ( this . _state = state ) === 'await' ) return ; this . lock = true ; Promise . resolve ( ) . then ( ( ) => { this . notify ( ) ; this . lock = false ; } ) ; } get state ( ) : state { return this . _state ; } attach ( persen ) { this . subs . push ( persen ) ; } notify ( ) { this . subs . forEach ( sub => { sub . update ( ) ; } ) ; } } class Tom extends Persen { constructor ( subject ) { super ( ) ; subject . attach ( this ) ; } update ( ) { console . log ( '通知到了 Tom' ) ; } } class Jick extends Persen { constructor ( subject ) { super ( ) ; subject . attach ( this ) ; } update ( ) { console . log ( '通知到了 Jick' ) ; } } const subject = new Subject ( ) ; new Tom ( subject ) ; new Jick ( subject ) ; subject . state = 'publish' ; subject . state = 'await' ; console . log ( subject . state ) ; subject . state = 'publish' ; setTimeout ( ( ) => { subject . state = 'publish' ; } , 1000 ) ;