package eventlistener;
import java.util.EventListener;
public interface ISwitchListener extends EventListener {
public void switchEvent(SwitchEvent event);
}
Copy the code
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(a) {
return this.switchState; }}Copy the code
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(a) {
if (listeners == null)
return;
SwitchEvent event = new SwitchEvent(this."open");
notifyListeners(event);
}
protected void fireSwitchOff(a) {
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); }}}Copy the code
package eventlistener;
public class SwitchTest {
public static void main(String[] args) {
SwitchManager manager = new SwitchManager();
manager.addDoorListener(newTVSwitchListener()); manager.fireSwitchOn(); manager.fireSwitchOff(); }}Copy the code
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"); }}}Copy the code