当前位置:网站首页>Implementation of asynchronous notification and event callback based on guava API

Implementation of asynchronous notification and event callback based on guava API

2022-06-24 01:31:00 Tom bomb architecture

This article is excerpted from 《 This is how design patterns should be learned 》

1  be based on Java API Implement notification mechanism

When friends ask questions in the community , If there is a setting, specify the user to answer , Then the corresponding user will receive an email notification , This is an application scenario of observer pattern . Some little friends may think MQ、 Asynchronous queue, etc , Actually JDK This is what it's all about API. We use code to restore such an application scenario , First create GPer class .

/**
 * JDK Provides an implementation of the observer , Observed 
 */
public class GPer extends Observable{
    private String name = "GPer ecosystem ";
    private static GPer gper = null;
    private GPer(){}

    public static GPer getInstance(){
        if(null == gper){
            gper = new GPer();
        }
        return gper;
    }
    public String getName() {
        return name;
    }
    public void publishQuestion(Question question){
        System.out.println(question.getUserName() + " stay " + this.name + " A question was asked on .");
        setChanged();
        notifyObservers(question);
    }
}

And then create the question Question class .

public class Question {
    private String userName;
    private String content;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

Then create a teacher Teacher class .

public class Teacher implements Observer {

    private String name;

    public Teacher(String name) {
        this.name = name;
    }

    public void update(Observable o, Object arg) {
        GPer gper = (GPer)o;
        Question question = (Question)arg;
        System.out.println("======================");
        System.out.println(name + " teacher , Hello !\n" + 
" You have received one from " + gper.getName() + " The question of , I hope you can answer . The questions are as follows :\n" +
                   question.getContent() + "\n" + " The questioner :" + question.getUserName());
    }
}

Finally, write client test code .

    public static void main(String[] args) {
        GPer gper = GPer.getInstance();
        Teacher tom = new Teacher("Tom");
        Teacher jerry = new Teacher("Jerry");

        gper.addObserver(tom);
        gper.addObserver(jerry);

        // User behavior 
        Question question = new Question();
        question.setUserName(" Zhang San ");
        question.setContent(" Which scenes are suitable for observer mode ?");

        gper.publishQuestion(question);
}

The results are shown in the following figure .

file

2  be based on Guava API Easy landing observer mode

The author recommends a very useful framework for implementing the observer pattern ,API It's very easy to use , for instance , First introduce Maven Dependency package .

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>20.0</version>
</dependency>

Then create a listening event GuavaEvent.

/**
 * Created by Tom
 */
public class GuavaEvent {
    @Subscribe
    public void subscribe(String str){
        // Business logic 
        System.out.println(" perform subscribe Method , The parameter passed in is :" + str);
    }

}

Finally, write client test code .

/**
 * Created by Tom
 */
public class GuavaEventTest {
    public static void main(String[] args) {
        EventBus eventbus = new EventBus();
        GuavaEvent guavaEvent = new GuavaEvent();
        eventbus.register(guavaEvent);
        eventbus.post("Tom");
    }

}

3  Use observer mode to design mouse event response API

Let's design a business scenario , Help partners better understand the observer model . stay JDK Source code , Observer mode is also widely used . for example java.awt.Event It's a kind of observer mode , It's just Java Rarely used to write desktop programs . Let's implement it in code , In order to help the partners to have a deeper understanding of the implementation principle of observer mode . First , establish EventListener Interface .

/**
 *  The observer abstracts 
 * Created by Tom.
 */
public interface EventListener {

}

establish Event class .

/**
 *  Definition of standard event source format 
 * Created by Tom.
 */
public class Event {
    // Event source , Who sent the action 
    private Object source;
    // Events trigger , Who should be informed ( The observer )
    private EventListener target;
    // Observer response 
    private Method callback;
    // Name of event 
    private String trigger;
    // The trigger event of the event 
    private long time;

    public Event(EventListener target, Method callback) {
        this.target = target;
        this.callback = callback;
    }

    public Object getSource() {
        return source;
    }

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

    public String getTrigger() {
        return trigger;
    }

    public Event setTrigger(String trigger) {
        this.trigger = trigger;
        return this;
    }

    public long getTime() {
        return time;
    }

    public Event setTime(long time) {
        this.time = time;
        return this;
    }

    public Method getCallback() {
        return callback;
    }

    public EventListener getTarget() {
        return target;
    }

    @Override
    public String toString() {
        return "Event{" +
                "source=" + source +
                ", target=" + target +
                ", callback=" + callback +
                ", trigger='" + trigger + '\'' +
                ", time=" + time +
                '}';
    }
}

establish EventContext class .

/**
 *  The abstraction of the observed 
 * Created by Tom.
 */
public abstract class EventContext {
    protected Map<String,Event> events = new HashMap<String,Event>();

    public void addListener(String eventType, EventListener target, Method callback){
        events.put(eventType,new Event(target,callback));
    }

    public void addListener(String eventType, EventListener target){
        try {
            this.addListener(eventType, target, 
target.getClass().getMethod("on"+toUpperFirstCase(eventType), Event.class));
        }catch (NoSuchMethodException e){
            return;
        }
    }

    private String toUpperFirstCase(String eventType) {
        char [] chars = eventType.toCharArray();
        chars[0] -= 32;
        return String.valueOf(chars);
    }

    private void trigger(Event event){
        event.setSource(this);
        event.setTime(System.currentTimeMillis());

        try {
            if (event.getCallback() != null) {
                // Call the callback function with reflection 
                event.getCallback().invoke(event.getTarget(), event);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    protected void trigger(String trigger){
        if(!this.events.containsKey(trigger)){return;}
        trigger(this.events.get(trigger).setTrigger(trigger));
    }
}

Then create MouseEventType Interface .

/**
 * Created by Tom.
 */
public interface MouseEventType {
    // single click 
    String ON_CLICK = "click";

    // double-click 
    String ON_DOUBLE_CLICK = "doubleClick";

    // Spring up 
    String ON_UP = "up";

    // Press down 
    String ON_DOWN = "down";

    // Move 
    String ON_MOVE = "move";

    // rolling 
    String ON_WHEEL = "wheel";

    // hover 
    String ON_OVER = "over";

    // Lose focus 
    String ON_BLUR = "blur";

    // Focus of attention 
    String ON_FOCUS = "focus";
}

establish Mouse class .

/**
 *  The specific observed 
 * Created by Tom.
 */
public class Mouse extends EventContext {

    public void click(){
        System.out.println(" Call the click method ");
        this.trigger(MouseEventType.ON_CLICK);
    }

    public void doubleClick(){
        System.out.println(" Call the double-click method ");
        this.trigger(MouseEventType.ON_DOUBLE_CLICK);
    }

    public void up(){
        System.out.println(" Call the bounce method ");
        this.trigger(MouseEventType.ON_UP);
    }

    public void down(){
        System.out.println(" Call the following method ");
        this.trigger(MouseEventType.ON_DOWN);
    }

    public void move(){
        System.out.println(" Call the move method ");
        this.trigger(MouseEventType.ON_MOVE);
    }

    public void wheel(){
        System.out.println(" Call the scroll method ");
        this.trigger(MouseEventType.ON_WHEEL);
    }

    public void over(){
        System.out.println(" Call the hover method ");
        this.trigger(MouseEventType.ON_OVER);
    }

    public void blur(){
        System.out.println(" Call the get focus method ");
        this.trigger(MouseEventType.ON_BLUR);
    }

    public void focus(){
        System.out.println(" Call the out of focus method ");
        this.trigger(MouseEventType.ON_FOCUS);
    }
}

Create callback method MouseEventLisenter class .

/**
 *  The observer 
 * Created by Tom.
 */
public class MouseEventListener implements EventListener {


    public void onClick(Event e){
        System.out.println("=========== Trigger mouse click event ==========" + "\n" + e);
    }

    public void onDoubleClick(Event e){
        System.out.println("=========== Trigger the mouse double click event ==========" + "\n" + e);
    }

    public void onUp(Event e){
        System.out.println("=========== Trigger the mouse pop-up event ==========" + "\n" + e);
    }

    public void onDown(Event e){
        System.out.println("=========== Trigger mouse down event ==========" + "\n" + e);
    }

    public void onMove(Event e){
        System.out.println("=========== Trigger the mouse movement event ==========" + "\n" + e);
    }

    public void onWheel(Event e){
        System.out.println("=========== Trigger the mouse scroll event ==========" + "\n" + e);
    }

    public void onOver(Event e){
        System.out.println("=========== Trigger mouse over event ==========" + "\n" + e);
    }

    public void onBlur(Event e){
        System.out.println("=========== Trigger the mouse out of focus event ==========" + "\n" + e);
    }

    public void onFocus(Event e){
        System.out.println("=========== Trigger the mouse to get focus event ==========" + "\n" + e);
    }

}

Finally, write client test code .

    public static void main(String[] args) {
        EventListener listener = new MouseEventListener();

        Mouse mouse = new Mouse();
        mouse.addListener(MouseEventType.ON_CLICK,listener);
        mouse.addListener(MouseEventType.ON_MOVE,listener);

        mouse.click();
        mouse.move();
    }
		

This paper is about “Tom Bomb architecture ” original , Reprint please indicate the source .

原网站

版权声明
本文为[Tom bomb architecture]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/11/20211117173901271j.html

随机推荐