目标

使用观察者模式更新信息,比如 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

参考

  1. 多达 2 万多颗小星星的开源项目 https://github.com/iluwatar/java-design-patterns
  2. java 并发编程实战


↙↙↙阅读原文可查看相关链接,并与作者交流