I'm practicing oop
concepts these days. To figure it out I tried the below problem.
There is a sensor monitoring system. It is a simple system that prints a value, whenever a sensor has picked a value.
I tried to solve this problem according to oop
and SOLID
principals.
So I created an interface SensorListener
interface SensorListener{
public void onValueUpdated(SensorTypes type, double value);
}
Then I created a Sensor
class
public class Sensor {
private int value;
private SensorTypes types;
private SensorListener sensorListener;
public Sensor(SensorTypes types) {
this.types = types;
}
public void setValue(int value) {
this.value = value;
sensorListener.onValueUpdated(types, value);
}
public void registerListener(SensorListener sensorListener) {
this.sensorListener = sensorListener;
}
}
For sensor types the enum
is as below
public enum SensorTypes {
TEMPERATURE, PH, HUMIDITY;
}
For the monitoring purpose I created a class SensorMonitor
that implements SensorListener`
public class SensorMonitor implements SensorListener {
@Override
public void onValueUpdated(SensorTypes type, double value) {
System.out.println("Sensor Name: " + type + ", Measure: " + value);
}
}
Finally in the main method I mocked the sensor updated using a Thread
,
public static void main(String[] args) {
SensorMonitor sensorMonitor = new SensorMonitor();
Sensor temperature = new Sensor(SensorTypes.TEMPERATURE);
temperature.registerListener(sensorMonitor);
Sensor humidity = new Sensor(SensorTypes.HUMIDITY);
humidity.registerListener(sensorMonitor);
Sensor pH = new Sensor(SensorTypes.PH);
pH.registerListener(sensorMonitor);
Thread thread = new Thread(() -> {
int i = 0;
while (true) {
try {
temperature.setValue(i++);
Thread.sleep(3000);
humidity.setValue(i++);
Thread.sleep(3000);
pH.setValue(i++);
Thread.sleep(3000);
} catch (InterruptedException e) {
System.out.println("thread interrupted");
}
}
});
thread.start();
}
In this way program successfully works and prints the output in 3 second intervals.
Sensor Name: TEMPERATURE, Measure: 0.0
Sensor Name: HUMIDITY, Measure: 1.0
Sensor Name: PH, Measure: 2.0
I'm satisfied with the behavior because it does what it says. But I'm not sure whether this a correct oop
way of implementing interfaces
and whether up to which context is this application scalable.
For example as the SensorMonitor
how can it know the details of currently operating sensors, and what sensors are in the monitoring process?
Can someone point out what are the pros and cons in my approach.
Is this conforms to SOLID principals?
I appreciate a more concise approach for this problem.