[Design Mode] -11 listener mode

table of Contents

 

1. What is the listeners mode

2. Composition of the listener mode (member)

3. code implementation

4. Thinking


1. What is the listeners mode

Listener mode in reality everywhere, give a common example, we often see in a movie clip, when the signal scouts received a command signal sent superiors, the appropriate action will be executed immediately. In ancient times, also there beacon, when the beacon is lit, the distance will immediately notify Sentinel observed soldiers began a similar defense of foreign enemies ... make the appropriate feedback immediately after receipt of such a "signal" after the smoke, said in the field of programming the pattern for the listener, so to speak in general terms, may be more easily confused with observer mode, the following details next listener mode.

2. Composition of the listener mode (member)

Listener mode source by the event, the event object, the three together constitute an event listener.

Event Source: being monitored the event itself, that is, something can trigger element listener, corresponding to the above example lighted beacon event.

Event object: the event object stored inside a reference to the event source, the event can be obtained through the event source object is a wrapper for the event source.

Event listeners: the definition of action after the incident, such as Beacon is the point then, they should immediately inform the soldiers defense listeners in the specific logic implemented by the developer.

3. code implementation

Just look at the above description may be relatively empty, even incomprehensible, as the ape or program code to be more direct.

First on a low version:

Scene: In my game like a chicken, for example, I like to lick dropped, almost every drop of the King of all, I feel like the top with, of course, in frequent killed ...

Once the game I saw someone put a gun signal, it will lick the last drop, use the following code to implement the next ...

Event Source:

public class SignalSource {
    private SignalListener signalListener;

    public void signal(){
        System.out.println("打响了信号枪...");
        if (signalListener!=null){
            signalListener.doGetAirDrop(new Signal(this));
        }
    }

    public SignalSource(SignalListener signalListener) {
        this.signalListener = signalListener;
    }
}

Event object:

public class Signal {
    private SignalSource signalSource;

    public SignalSource getSignalSource() {
        return signalSource;
    }

    public void setSignalSource(SignalSource signalSource) {
        this.signalSource = signalSource;
    }

    public Signal(SignalSource signalSource) {
        this.signalSource = signalSource;
    }
}

Listener:

public interface SignalListener {
    void doGetAirDrop(Signal signal);
}

test:

public class Client {
    public static void main(String[] args) {
        SignalSource signalSource = new SignalSource((s)->{
            System.out.println("看到有人在打信号枪,我要去舔空投了...");
        });
        signalSource.signal();
    }
}

result:

Then it can be seen, when the event source is triggered, the listener where the logic is executed. That is fired the flare gun, I began to lick the drop. The above is a simple implementation listener mode, see here, you are there the same question to me, and continue to look down.

4. Thinking

Why there is a Signal (event object)? Directly trigger the listener in the logic does not like it in the event source inside? To have it with eggs ???

If after I put Signal (event object) removed, it becomes a special What does the observer mode ??? 

Meaning there must exist, since the 23 design patterns in the observer mode and listener mode classified as different design patterns, it must have its reasons.

To address this question, the next may wish to think, if the event is not the source signal gun fired, but someone threw a grenade into it? That the action to be performed at this time should be quickly lie down or avoid, rather than lick airdrop. in the actual business, often need to monitor the event sources are diverse and have different listeners for different event sources need to follow up, this time without the event object, it will be like the observer pattern, once the event trigger source, monitor all events will be triggered, which is obviously unreasonable, someone put a gun I would also signal to lie down or avoid ???

The above code does not seem very well reflected this, but can help us better understand the listener mode, world affairs, will do to the easy.

Now I wrote a fairly standard listener mode, inherited from JDK achieve the standard library, in the actual development and multi-source Spring this way:

I also at the same above scenario as an example, are analog monitor signals guns and grenades and other events:

Event Source:

public class EventSource {
    private List<Listener> listenerList = new ArrayList<>();

    public void fireEvent(EventObject event) {
        listenerList.parallelStream()
            .distinct()
            .collect(Collectors.toList())
            .forEach(l -> l.invoke(event));
    }

    public void addListener(Listener listener) {
        if (listener != null) {
            listenerList.add(listener);
        }
    }

    public void removeListener(Listener listener) {
        if (listener != null) {
            listenerList.remove(listener);
        }
    }
}

Event object:

//继承自Java.util.EventObject
public class Event extends EventObject {
    private Object source;
    private Integer state;

    public Event(Object source) {
        super(source);
    }

    @Override
    public Object getSource() {
        return source;
    }

    public void setSource(Object source) {
        this.source = source;
    }

    public Integer getState() {
        return state;
    }

    public void setState(Integer state) {
        this.state = state;
    }
}

Listener:

//继承自java.util.EventListener
public interface Listener extends EventListener {
    void invoke(EventObject event);
}

Listener implementation class:

//针对打信号枪事件的监听
public class SignalListener implements Listener {
    @Override
    public void invoke(EventObject eventObject) {
        Event event = (Event)eventObject;
        if (Objects.equals(event.getState(),StateEnum.SIGNAL.getState())){
            System.out.println("有人打信号枪了,我要去舔空投...");
        }
    }
}
//针对扔手雷事件的监听
public class BoomListener implements Listener {
    @Override
    public void invoke(EventObject eventObject) {
      Event event = (Event)eventObject;
      if (Objects.equals(event.getState(),StateEnum.BOOM.getState())){
          System.out.println("有人扔手雷了,我要卧倒或者躲避...");
      }
    }
}

State management enumeration class:

public enum StateEnum {
    SIGNAL(1),
    BOOM(2)
    ;
    private Integer state;

    StateEnum(Integer state) {
        this.state = state;
    }

    public Integer getState() {
        return state;
    }

    public void setState(Integer state) {
        this.state = state;
    }
}

Test categories:

public class Client {
    public static void main(String[] args) {
        EventSource eventSource = new EventSource();
        SignalListener signalListener = new SignalListener();
        BoomListener boomListener = new BoomListener();
        eventSource.addListener(signalListener);
        eventSource.addListener(boomListener);
        Event event = new Event(eventSource);
        event.setState(StateEnum.SIGNAL.getState());
        eventSource.fireEvent(event);
        event.setState(StateEnum.BOOM.getState());
        eventSource.fireEvent(event);
    }
}

effect:

Can be achieved by a specific event status is monitored on a specified event, hot-plug can also be achieved by addListener of listeners and removeListener event source, do I want to listen what events, what events would listen, I do not want to listen for events not listening, so we can see, the listener model seems functionally more flexible than the observer mode, but realize the difficulty and complexity than the observer mode, in short, each application scenarios, they can utilize.

If you still reading this for the listener and observer mode pattern is not clear enough, nor good correspondence using the corresponding design patterns at the scene, it does not matter, I can refer to explain listener and observer mode mode in the next.

Published 89 original articles · won praise 69 · views 40000 +

Guess you like

Origin blog.csdn.net/lovexiaotaozi/article/details/102579880