通用技术 [设计模式] 观察者模式的学习及使用

bauul · 2017年08月21日 · 最后由 bauul 回复于 2017年08月23日 · 4863 次阅读

目标

使用观察者模式更新信息,比如 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 并发编程实战
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
共收到 6 条回复 时间 点赞

来个全套吧?

恒温 回复

可以啊,等我学完的
😈

打印出来是什么东东呢?

南京地铁站,无法吐槽

回复

肿么了?

Keyens 回复

已更新

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册