Observer mode

xiaoxiao2021-03-06  65

Class Observer

{

Private function observer () {}

//Methods

PUBLIC FUNCTION UPDATE (): Void {};

}

Class Subject

{

// fields

Private var observers: array = new array ();

Private function subject ()

{

}

//Methods

Public Function Attach (OBServer: Observer): Void

{

Observers.push (Observer);

}

Public Function DETACH (OBSERVER: OBSERVER): Void

{

Observers.shift (OBServer);

}

Public function notify (): void

{

// trace (observers);

For (var i = 0; i

{

Observers [i] .update ();

}

}

}

Class ConcreteobServer Extends Observer

{

// fields

Private var name: String;

Private var observerstate: string;

PRIVATE VAR SUBJECT: CONCRESUBJECT;

// conntructors

Public Function ConcreteobServer (Sub: ConcreteSubject, N: String)

{

Subject = SUB;

Name = n;

// trace (SUBJECT ":" N);

}

//Methods

Public function update (): void

{

//trace(Subject.SubjectState;

Observerstate = Subject.subjectState;

"Observer" Name "'s new state is" observerstate);

}

// Properties

Public function get subject (): concreteSubject

{

Return Subject;

}

Public Function Set Subject (Value: ConcreteSubject): VoID

{

Subject = Value;

}

}

Class ConcreeSubject Extends Subject

{

// fields

PRIVATE VAR SUBJECTSTATATE: STRING;

Public function get SubjectState (): String

{

Return SubjectState;

}

Public Function Set SubjectState (Value: String): Void

{

SubjectState = Value;

}

}

//client.fla

Var s: ConcreteSubject = New ConcReSubject ();

S.Attach (New ConcreteobServer (S, "X"));

S.Attach (New Concreteobserver (S, "Y"));

S.Attach (New Concreteobserver (S, Z "));

// Change Subject and Notify Observers

S.SUBJECTSTATE = "abc"; s.Notify ();

// Output:

// Observer x's new state is abc

// Observer Y's New State Is Abc

// Observer Z's New State Is Abc

This mode is too important, MVC is often used! It is generally the action of monitoring the view, change the Model via Control.

转载请注明原文地址:https://www.9cbs.com/read-119504.html

New Post(0)