A Java simulation of an infrared beam sensor system using the Observer pattern. The sensor detects whether an object is blocking an infrared beam and notifies all registered observers, each reacting independently.
| Class/Interface | Role |
|---|---|
IrSensor |
The observed. Runs on a separate thread, polls beam state every second via AtomicBoolean, notifies observers on state change |
SensorObserver |
Interface with a single method onStateChanged(State state) |
Gate |
Observer. Starts a 5-second countdown to close when beam is clear. Cancels it if beam is blocked again |
AlarmSystem |
Observer. Alerts security 5 seconds after detecting an intruder. Cancels if beam clears |
SimulatedEnvironment |
Reads keyboard input to simulate objects passing through the beam |
Main |
Wires all components together and starts the sensor thread |
- Java 17+
- No external dependencies
Launch Main.java from your IDE or via terminal:
javac -d out src/com/main/*.java
java -cp out com.main.Main| Key | Action |
|---|---|
b |
Block the beam (object detected) |
c |
Clear the beam (no object) |
q |
Quit |
To add a new observer, create a class that implements SensorObserver
and register it in Main with irSensor.addObserver(yourObserver).