package eventlistener;
import java.util.EventListener;
public interface ISwitchListener extends EventListener {
public void switchEvent(SwitchEvent event);
}
package eventlistener;
import java.util.EventObject;
("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 {
public void switchEvent(SwitchEvent event) {
if (event.getSwitchState() != null && event.getSwitchState().equals("open")) {
System.out.println("open TV");
} else {
System.out.println("close TV");
}
}
}