📄 pump.java
字号:
package examples.observe;
import java.util.Observable;
import java.util.Observer;
/** Class to demonstrate the use of the Observer
* interface and the Observable class
*/
public class Pump {
/** Method for creating a Pump, a Valve, and
* a Buzzer object and connecting the Valve
* and Buzzer objects together
* @param args not used
*/
public static void main( String[] args ) {
Pump p = new Pump();
Valve v = p.new Valve();
Buzzer b = p.new Buzzer();
v.addObserver( b );
v.setPressure( 150 );
v.setPressure( 200 );
v.setPressure( 75 );
}
/** A class representing a valve in a pump
* that can be observed by other objects
*/
private class Valve extends Observable {
private int pressure;
/** Method used to set the pressure at
* the valve. It notifies its
* observers of the change
* @param p Updated pressure value
*/
public void setPressure( int p ) {
pressure = p;
setChanged();
notifyObservers();
}
public int getPressure() {
return pressure;
}
}
/** Class representing the warning buzzer on a
* pump. The buzzer sounds when the pressure
* of the valve it is observing exceeds the
* threshold, and goes silent when the pressure
* drops back below the threshold.
*/
private class Buzzer implements Observer {
private int threshold = 100;
private boolean buzzerOn;
/** This method is called whenever the valve
* being observed changes
* @param o the object under observation
* @param arg optional argument, not used
*/
public void update( Observable o, Object arg ) {
Valve v = (Valve) o;
if ( v.getPressure() > threshold
&& buzzerOn == false ) {
buzzerOn = true;
System.out.println( "Buzzer on" );
} else if ( v.getPressure() < threshold
&& buzzerOn == true ) {
buzzerOn = false;
System.out.println( "Buzzer off" );
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -