使用Java标准的java.util.EventListener实现观察者-发布者设计模式

package eventlistener;

import java.util.EventListener;

public interface ISwitchListener extends EventListener {
    public void switchEvent(SwitchEvent event);
}

package eventlistener;

import java.util.EventObject;

@SuppressWarnings("serial")
public class SwitchEvent extends EventObject implements Cloneable {

    private String switchState = "";

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

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

    public String getSwitchState() {
        return this.switchState;
    }
}

package eventlistener;

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;

public class SwitchManager {
    private Collection<ISwitchListener> listeners;

    public void addDoorListener(ISwitchListener listener) {
        if (listeners == null) {
            listeners = new HashSet<ISwitchListener>();
        }
        listeners.add(listener);
    }

    public void removeDoorListener(ISwitchListener listener) {
        if (listeners == null)
            return;
        listeners.remove(listener);
    }

    protected void fireSwitchOn() {
        if (listeners == null)
            return;
        SwitchEvent event = new SwitchEvent(this, "open");
        notifyListeners(event);
    }

    protected void fireSwitchOff() {
        if (listeners == null)
            return;
        SwitchEvent event = new SwitchEvent(this, "close");
        notifyListeners(event);
    }

    private void notifyListeners(SwitchEvent event) {
        Iterator<ISwitchListener> iter = listeners.iterator();
        while (iter.hasNext()) {
        	ISwitchListener listener = (ISwitchListener) iter.next();
            listener.switchEvent(event);
        }
    }
}

package eventlistener;

public class SwitchTest {

	public static void main(String[] args) {
		SwitchManager manager = new SwitchManager();
        manager.addDoorListener(new TVSwitchListener());

        manager.fireSwitchOn();
        manager.fireSwitchOff();

	}

}


package eventlistener;

public class TVSwitchListener implements ISwitchListener {
    @Override
    public void switchEvent(SwitchEvent event) {

        if (event.getSwitchState() != null && event.getSwitchState().equals("open")) {
            System.out.println("open TV");
        } else {
            System.out.println("close TV");
        }
    }
}

展开阅读全文
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值