Reputation: 23
I'm new in the Java world and struggle a little bit with my application. I divided my application into several layers (UI, controller, ...). The bottom layer is responsible for gathering data from sensors.
My goal is to make this layer extensible, such that external users/programmers could easily add new sensors in it.
Do I only have to separate each sensor in a distinct class or is there any other solution for it?
My apologies if it's a 'weird' question, I'm just a newbie :)
Thanks!
Upvotes: 1
Views: 333
Reputation: 21686
Essentially what you are building is a framework. The sensor code would follow the Hollywood Principle: "don't call me, I'll call you"
This is achieved by applying the Dependency Inversion Principle.
You create an interface Sensor.java:
public interface Sensor {
Reading getReading();
}
And a Reading.java (making this general is an Open Closed Principle challenge related to how much generality you need from sensor data structures):
public final class Reading {
}
And a a SensorReader.java:
public final class SensorReader {
private final Iterable<Sensor> sensors;
public SensorReader(Iterable<Sensor> sensors) {
this.sensors = sensors;
}
public void readSensors() {
for (Sensor sensor : sensors) {
Reading reading = sensor.getReading();
// so stuff with reading
}
}
}
Everything above here is framework, everything past here is application/client code.
And a MotorEncoder.java:
final class MotorEncoder implements Sensor {
@Override
public Reading getReading() {
// do stuff to actually read motor encoder
return new Reading();
}
}
And an Application.java:
import java.util.Arrays;
public final class Application {
public static void main(String[] args) {
Sensor sensor = new MotorEncoder();
SensorReader sensorReader = new SensorReader(Arrays.asList(sensor));
sensorReader.readSensors();
}
}
Upvotes: 1
Reputation: 10552
You can use many mechanisms. For example Spring. You can define beans and include them during runtime (put in a folder), but the beans must implement some well defined interfaces.
Another solution would be to use some design patterns such as
Upvotes: 0
Reputation: 23029
The bottom layer can have List<Gatherer> gatherers
variable. Gatherer should be interface with methods important for the bottom layer.
Anyone can then create its own Gatherer and register it to your layer.
The bottom layer is responsible for executing gatherers, registering/removing them etc.
Upvotes: 1