我相信我们公司有一个边缘案例,这阻止了我进入“从不使用全局变量阵营”。
我们需要编写一个嵌入式应用程序,它可以在我们的机器中工作,从医院的设备中提取医疗数据。
这应该是无限运行的,即使当医疗设备被关闭,网络消失,或我们的盒子的设置发生变化。设置是从.txt文件中读取的,该文件可以在运行时进行更改,最好没有问题。
这就是单例模式对我没有用处的原因。因此,我们会不时地返回(在读取1000个数据之后),并像这样读取设置:
public static SettingForIncubator settings;
public static void main(String[] args) {
while(true){
settings = getSettings(args);
int counter=0;
while(medicalDeviceIsGivingData && counter < 1000){
byte[] data = readData(); //using settings
//a lot of of other functions that use settings.
counter++;
}
Thread.Sleep(100); //against overheating and CPU usage.
}
public byte[] readData(){
//read Data from the port described in settings variable
}
}还有没有其他方法可以设计这个程序?
发布于 2019-12-27 00:48:40
我不知道你到底是什么意思,但我认为这段代码会对你有所帮助:
class SettingsForIncubator {
}
public class MedicalProcessor {
protected volatile boolean active;
protected volatile boolean medicalDeviceIsGivingData;
public void start(String[] args) throws Exception {
this.active = true;
Thread thread = new Thread(() -> loop(args));
thread.start();
}
protected void loop(String[] args) {
System.out.println("start");
while(active) {
SettingsForIncubator settings = getSettings(args);
int counter=0;
while(medicalDeviceIsGivingData && counter < 1000){
byte[] data = readData(settings); //using settings
//a lot of of other functions that use settings.
counter++;
}
try {
Thread.sleep(100); //against overheating and CPU usage.
}
catch (Exception e) {
break;
}
}
}
protected byte[] readData(SettingsForIncubator settings) {
// logic read data
return null;
}
protected SettingsForIncubator getSettings(String[] args) {
// logic to get settings
return null;
}
public void stop() {
this.active = false;
}
public static void main(String[] args) throws Exception {
MedicalProcessor processor = new MedicalProcessor();
processor.start(args);
}
}https://stackoverflow.com/questions/59490348
复制相似问题