Observer mode

xiaoxiao2021-03-06  70

Observer mode

Page 2 (3 pages a total)

Observer is a very common pattern. This mode is usually used when you implement an application with the Model / View / Controller (Model / View / Controller "architecture. The "Model / View" section of this design is to remove data indicating the coupling of the data itself. For example, it is envisioned that the data is saved in the database, which can be displayed in a variety of formats (tables or graphics). Observer mode recommends that the class registers themselves to the class responsible for maintaining the data, so that the display class can be notified when the data changes, so they can update their display. The Java API uses this mode in its event model of its AWT / SWING class. It also provides direct support so that this mode can be implemented for other purposes. The Java API provides an OBSERVABLE class that can be subclassified by objects to be observed. Observable provides the following methods:

Observable object calls AddobServer (Observer O) to register yourself. SetChanged () labeled OBSERVABLE objects as changed. Haschanged () Tests if the OBSERVABLE object has changed. According to Haschanged (), if the OBSERVABLE object has changed, NotifyObservers () notifies all observations. Correspondingly, an OBServer interface is also provided, which contains a method called when it occurs when it changes it. (Of course, it is the premise that Observer has registered with the OBSERVABLE class):

Public void Update (Observable O, Object Arg)

The following example demonstrates how to use the OBServer mode to notify the display class such as temperature and other sensors has been detected:

Import java.util. *;

Class Sensor Extends Observable {

Private int TEMP = 68;

Void takereading ()

{

Double D;

D = math.random ();

IF (D> 0.75)

{

TEMP ;

setChanged ();

}

ELSE IF (D <0.25)

{

TEMP -;

setChanged ();

}

System.out.print ("[Temp:" TEMP "]");

}

Public int getReading ()

{

Return Temp;

}

}

Public class display imports observer {

Public void Update (Observable O, Object Arg)

{

System.out.print ("New Temp:" ((Sensor) O) .getReading ());

}

Public static void main (String [] AC)

{

Sensor Sensor = New Sensor ();

Display display = new display ();

// Register Observer with Observable Class

Sensor.Addobserver (Display);

// Simulate Measuring Temp over Time

For (int i = 0; i <20; i )

{

Sensor.takeReading (); Sensor.notifyObservers ();

SYSTEM.OUT.PRINTLN ();

}

}

}

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

New Post(0)