监听器

/////////// ListenableProperties /////////////
/**
 * Properties 本质上是一个HashTable,每次读写都会加锁,所以不支持频繁的System.getProperty(name)来检查系统内容变化 因此扩展了一个ListenableProperties,
 * 在其所关心的属性变化时进行通知.
 * 
 * @see ListenableProperties
 */
public static synchronized void registerSystemPropertiesListener(PropertiesListener listener) {
    Properties currentProperties = System.getProperties();

    // 将System的properties实现替换为ListenableProperties
    if (!(currentProperties instanceof ListenableProperties)) {
        ListenableProperties newProperties = new ListenableProperties(currentProperties);
        System.setProperties(newProperties);
        currentProperties = newProperties;
    }

    ((ListenableProperties) currentProperties).register(listener);
}

/**
 * Properties 本质上是一个HashTable,每次读写都会加锁,所以不支持频繁的System.getProperty(name)来检查系统内容变化 因此扩展了Properties子类,
 * 在其所关心的属性变化时进行通知.
 * 
 * @see PropertiesListener
 */
public static class ListenableProperties extends Properties {

    private static final long serialVersionUID = -8282465702074684324L;

    protected transient List listeners = new CopyOnWriteArrayList();

    public ListenableProperties(Properties properties) {
        super(properties);
    }

    public void register(PropertiesListener listener) {
        listeners.add(listener);
    }

    @Override
    public synchronized Object setProperty(String key, String value) {
        Object result = put(key, value);
        for (PropertiesListener listener : listeners) {
            if (listener.propertyName.equals(key)) {
                listener.onChange(key, value);
            }
        }
        return result;
    }
}

/**
 * 获取所关心的Property变更的Listener基类.
 */
public abstract static class PropertiesListener {

    // 关心的Property
    protected String propertyName;

    public PropertiesListener(String propertyName) {
        this.propertyName = propertyName;
    }

    public abstract void onChange(String propertyName, String value);
}




public void listenableProperties() {
    String name = "ss.test" + RandomUtil.nextInt();

    TestPropertiesListener listener = new TestPropertiesListener(name);
    SystemPropertiesUtil.registerSystemPropertiesListener(listener);

    System.setProperty(name, "haha");

    assertThat(listener.newValue).isEqualTo("haha");
}

public static class TestPropertiesListener extends PropertiesListener {

    public TestPropertiesListener(String propertyName) {
        super(propertyName);
    }

    public String newValue;

    @Override
    public void onChange(String propertyName, String value) {
        newValue = value;
    }

};

你可能感兴趣的:(监听器)