使用观察者模式更新信息,比如 Cpu, Memory, Battery...
package com.carl.observerdemo;
public interface AppInfoObserver {
void updateAppInfo ();
}
package com.carl.observerdemo;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AppInfo {
private static final Logger LOGGER = LoggerFactory.getLogger(AppInfo.class);
private List<AppInfoObserver> observers;
public AppInfo() {
observers = new ArrayList<>();
}
public void addObserver(AppInfoObserver obs) {
observers.add(obs);
}
public void removeObserver(AppInfoObserver obs) {
observers.remove(obs);
}
public void start() {
LOGGER.info("notifyObservers");
notifyObservers();
}
private void notifyObservers() {
for (AppInfoObserver obs : observers) {
obs.updateAppInfo();
}
}
}
package com.carl.observerdemo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.carl.utils.ThreadPoolUtils;
public class Battery implements AppInfoObserver {
private static final Logger LOGGER = LoggerFactory.getLogger(Battery.class);
@Override
public void updateAppInfo() {
LOGGER.info("battery update start");
ThreadPoolUtils.getThreadPool().execute(new Runnable() {
@Override
public void run() {
LOGGER.info("battery update run");
}
});
}
}
package com.carl.observerdemo;
public class Main {
static String[] stablityDataClassName = {"com.carl.observerdemo.Cpu",
"com.carl.observerdemo.Battery",
"com.carl.observerdemo.Memory"};
public static void main(String[] args) {
AppInfo appInfo = new AppInfo();
try {
for (String s : stablityDataClassName) {
Class<?> clazz = Class.forName(s);
appInfo.addObserver((AppInfoObserver)clazz.newInstance());
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
// Cpu cpu = new Cpu();
// Battery battery = new Battery();
// Memory memory = new Memory();
//
// appInfo.addObserver(cpu);
// appInfo.addObserver(battery);
// appInfo.addObserver(memory);
appInfo.start();
// appInfo.removeObserver(cpu);
// appInfo.removeObserver(battery);
// appInfo.removeObserver(memory);
}
}
package com.carl.utils;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolUtils {
private static ExecutorService threadPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1);
private ThreadPoolUtils(){
}
public static ExecutorService getThreadPool() {
return threadPool;
}
}
20:23:19.010 [main] INFO com.carl.observerdemo.AppInfo - notifyObservers
20:23:19.014 [main] INFO com.carl.observerdemo.Cpu - cpu update start
20:23:19.038 [main] INFO com.carl.observerdemo.Battery - battery update start
20:23:19.038 [pool-1-thread-1] INFO com.carl.observerdemo.Cpu - cpu update run
20:23:19.055 [main] INFO com.carl.observerdemo.Memory - memory update start
20:23:19.055 [pool-1-thread-2] INFO com.carl.observerdemo.Battery - battery update run
20:23:19.080 [pool-1-thread-3] INFO com.carl.observerdemo.Memory - memory update run