监听者模式示例

public class SwitchMain {

    public static void main(String[] args) {
        Switch switchTest = new Switch();
        switchTest.addListener(new SwitchListener() {
            public void handle(SwitchEvent switchEvent) {
                //Do what ever you want !
                System.out.println("可对该事件进行二次处理: "+switchEvent.getSwitchState());
            }
			public void handle() {
				//SwitchListener=callBack
				 System.out.println("回调执行复杂操作");
				
			}
        });
        //触发
        switchTest.call();
        switchTest.close();
    }
}
/*
 * 类似于Swing中的button
 * 1.添加监听者
 * 2.定义事件同时通知监听者
*/
class Switch {
	private SwitchListener callBack;
	
	public void addListener(SwitchListener callBack){
		this.callBack = callBack;
	}
	
	//此时为回调方法  没有监听者概念
	public void call(){
		callBack.handle();
		//SwitchEvent switchEvent = new SwitchEvent( this, "关");
		//callBack.handle(switchEvent);
	}
	
	public void close(){
		SwitchEvent switchEvent = new SwitchEvent( this, "关");
		notifyListeners(switchEvent);
	}
	
	private void notifyListeners (SwitchEvent switchEvent) {
		callBack.handle(switchEvent);
 }

}
class SwitchEvent  {

    private String switchState;     //表示开关的状态

    public SwitchEvent(Switch source, String switchState) {
        this.switchState = switchState;
    }

    public void setSwitchState(String switchState) {
        this.switchState = switchState;
    }

    public String getSwitchState() {
        return switchState;
    }
}
interface SwitchListener {
	//SwitchListener=callBack()
    void handle();//基于回调的观察者模式
    
    void handle(SwitchEvent event);//支持指定处理事件
}


示例2:监听文件的变化

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class App{
    public static void main( String[] args ) {
    	List<ModulesListener> modules = new ArrayList<ModulesListener>();
    	ModulesListener listener = new ModulesListener("custom.properties");
        listener.addConfigurationListener(new ConfigurationListener() {
            public void configurationChanged(ConfigurationEvent event) {
                System.out.println("ConfigurationListener, " + event.getType() + ", " + event.getModules());
            }
        });
        listener.addKeyListener("name", new PropertiesKeyListener() {
            public void configurationChanged(ConfigurationEvent event, String key, String value) {
                System.out.println("PropertiesKeyListener, " + key + " = " + value);
            }
        });
        ModulesListener listener2 = new ModulesListener("system.properties");
        listener2.addConfigurationListener(new ConfigurationListener() {
            public void configurationChanged(ConfigurationEvent event) {
                System.out.println("ConfigurationListener2, " + event.getType() + ", " + event.getModules());
            }
        });
        listener2.addKeyListener("name", new PropertiesKeyListener() {
            public void configurationChanged(ConfigurationEvent event, String key, String value) {
                System.out.println("PropertiesKeyListener2, " + key + " = " + value);
            }
        });
        modules.add(listener);
        modules.add(listener2);
    	SysProperties.getInstance().addListener(modules);
    	
    }
}
interface ConfigurationListener {
	void configurationChanged(ConfigurationEvent event);
}
interface PropertiesKeyListener {
    void configurationChanged(ConfigurationEvent event, String key, String value);
}

class ConfigurationEvent{
    private EventType type;
    private String modules;
    public ConfigurationEvent(Object source, EventType type) {
        this.type = type;
    }
    public EventType getType() {
        return type;
    }
    public void setType(EventType type) {
        this.type = type;
    }
    public String getModules() {
        return modules;
    }
    public void setModules(String modules) {
        this.modules = modules;
    }
}
class ModulesListener {
    private String name;
    private List<ConfigurationListener> configurationListeners = new ArrayList<ConfigurationListener>();
    private Map<String, PropertiesKeyListener> keyListeners = new HashMap<String, PropertiesKeyListener>();

    public ModulesListener(String name) {
        this.name = name;
    }
	public String getName() {
		return name;
	}
    /**
     * 新增模块更新监听
     *
     * @param listener 监听接口
     */
    public void addConfigurationListener(ConfigurationListener listener) {
        configurationListeners.add(listener);
    }
    /**
     * 新增Properties模块key更新监听
     * @param key 配置项
     * @param listener 监听接口
     */
    public void addKeyListener(String key, PropertiesKeyListener listener) {
        keyListeners.put(key, listener);
    }

    /**
     * 模块更新监听,动作执行
     *
     * @param event
     */
    public void actionConfigurationListener(ConfigurationEvent event) {
        for (ConfigurationListener listener : configurationListeners) {
            listener.configurationChanged(event);
        }
    }
    /**
     * Properties模块key更新监听,动作执行
     *
     * @param event
     * @param key
     * @param value
     */
    public void actionKeyListeners(ConfigurationEvent event, String key, String value) {
        if (keyListeners.containsKey(key)) {
            keyListeners.get(key).configurationChanged(event, key, value);
        }
    }
}
enum EventType {
	ADD, UPDATE, CLEAR;
}

import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;


/**
 * 读取实时的配置文件信息
 */
public class SysProperties {

	private Map<String, Long> lastModifMap = new HashMap<String, Long>();

	private static SysProperties instance;

	 private Map<String, ModulesListener> modulesListeners = new HashMap<String, ModulesListener>();

	public static SysProperties getInstance() {
		if (instance == null) {
			instance = new SysProperties();
		}
		return instance;
	}

	public void addListener(List<ModulesListener> modules) {
		for(ModulesListener listener:modules){
			modulesListeners.put(listener.getName(), listener);
		}
	}

	/**
	 * @description 私有构造器启动一个线程实时监控配置文件
	 */
	public SysProperties() {

		// 循环监控配置文件的变化,一旦发现文件发生变化了则重读配置文件
		Thread t = new Thread() {
			public void run() {
				while (true) {
					// 间隔1秒
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
					}

					try {
						String path = SysProperties.class.getClass().getResource("/config").getPath();
						File[] tmps = new File(path).listFiles();
						//File[] tmps = new File("E:\\Projects\\JavaProjects\\demo\\src\\main\\resources\\config").listFiles();
						for (File file : tmps) {
							if (file.exists()) {
		                        long l = file.lastModified(); // this can also throw a SecurityException

		                        String fileAbsPath = file.getAbsolutePath();
		                        long lastModif = getLastModif(fileAbsPath);

		                        if (l > lastModif) { // however, if we reached this point this
		                        	recordLastModify(fileAbsPath, l);
		                        	ConfigurationEvent event = null;
		                        	//不知道删除事件
		                        	if(lastModif == 0){
		                        		event = new ConfigurationEvent(file.getName(), EventType.ADD);
										
		                        	}else{
		                        		event = new ConfigurationEvent(file.getName(), EventType.UPDATE);
		                        	}
		                        	event.setModules(file.getName());
		                        	//无法精确key的变化	
									if(modulesListeners.containsKey(file.getName())){
										ModulesListener listener = modulesListeners.get(file.getName());
										Properties properties = transTo(file);
										listener.actionConfigurationListener(event);
										
										listener.actionKeyListeners(event, "name", properties.getProperty("name"));
									}
										
								
		                        }
		                    }
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		};
		t.start();
	}

	
	
	private long getLastModif(String key) {
        long lastModif = 0;
        if (lastModifMap.get(key) != null) {
            lastModif = lastModifMap.get(key).longValue();
        }
        return lastModif;
    }

    private void recordLastModify(String key, Long lastModif) {
        lastModifMap.put(key, lastModif);
    }

    public Properties transTo(File propertyFile){
    	Properties properties = new Properties();
    	FileInputStream inputStreamLocal = null;
		try {
			inputStreamLocal = new FileInputStream(propertyFile);
			properties.load(inputStreamLocal);
			return properties;
		}catch(Exception e){
			e.printStackTrace();
		}
		return properties;
    }
	

}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值