After reading Journey to the West for so many years, do you know how Sun Wukong summoned the father-in-law of the land?

Time:2022-9-18

The happiest thing when I was a child was lying on the sofa and watching "Journey to the West". The havoc in the heavenly palace, the three dozen white bone spirits, the real and fake Monkey King…a series of wonderful stories haunting my mind.

I don't know if you have noticed this detail: whenever Sun Wukong arrives in a new environment and needs to know the local "customs and customs", he will wave the golden hoop to summon the land. So, do you know what is the principle of Eunuch Land receiving Monkey King's summons?

event notification mechanism

We can first understand it as "event notification mechanism”, that is, whenever Sun Wukong knocks the golden hoop stick on the ground, it is equivalent to sending an email notification to the land, telling him that my old grandson is here, come out to pick him up quickly. When the land receives the notification, it will immediately Appeared.

Everyone knows that Spring has provided us withEvent monitoring, subscriptionNext, we use code to implement this scenario.

First of all, we have to define an event to record the action of Monkey King knocking on the ground.

@Getter
public class MonkeyKingEvent extends ApplicationEvent {

    private MonkeyKing monkeyKing;

    public MonkeyKingEvent(MonkeyKing monkeyKing) {
        super("monkeyKing");
        this.monkeyKing = monkeyKing;
    }

}

inMonkeyKingIt is the entity class of Sun Wukong we defined

@Data
public class MonkeyKing {

    /**
     * Whether to knock the ground, the default is no
     **/
    private boolean knockGround = false;

}

Then we need to implementApplicationListenerTo monitor the movements of Sun Wukong's knocking on the ground.

@Component
public class MyGuardianListener implements ApplicationListener {

    @Override
    public void onApplicationEvent(MonkeyKingEvent event) {
        boolean knockGround = event.getMonkeyKing().isKnockGround();
        if(knockGround){
            MyGuardian.appear();
        }else{
            MyGuardian.seclusion();
        }
    }
}

Finally, let's verify the whole process.

@PostMapping
public void testEvent(@RequestParam boolean knockGround) {
    MonkeyKing monkeyKing = new MonkeyKing();
    monkeyKing.setKnockGround(knockGround);
    MonkeyKingEvent monkeyKingEvent = new MonkeyKingEvent(monkeyKing);
    //Publish the action event of Sun Wukong knocking on the ground
    applicationEventPublisher.publishEvent(monkeyKingEvent);
}

when we calltestEvent()method passed inknockGroundfortrue, print

Landlord appeared

incoming asfalse, print

The land man has escaped

In this way, we simply realized the function of "Monkey King Summons the Land". Do you think this is the end? Since childhood, our teachers have taught us to "know the truth, but also know the reason".

Everyone said that reading the source code is more like drinking coffee. In order not to affect everyone's good mood, we will not study its source code here, we will go straight to Huanglong.

Observer pattern

Said to beevent notification mechanismyes,event listener – subscriptionRegardless of the implementation, in fact, its internal final implementation principle relies on the observer pattern. Seeing this, don't be timid, don't feel that the design pattern is obscure and difficult to understand for a long time. Today I will use an easy-to-understand little story to bring you a new understanding of the observer mode.

The story is like this. Above we only talked about the action of Sun Wukong knocking on the ground, but do you still remember that when Sun Wukong pointed the golden hoop stick to the sky, he exchanged for the Thunder God, the Dragon King, etc. to cast spells and rain for him? Closing his eyes, he still remembers the scene of the contest with Hu Li Daxian.

It can be seen that not only the land can receive the notice of Sun Wukong, but also the Thunder God and the Dragon King. Here, we compare Sun Wukong to the subject, that is, the observed andSubjectThe concept of thunder and lightning, the dragon king and the land are likened to observers.

Here is our code logic:

First, we define the base class of a topic, which records a list of all observers subscribed to the topic, and also includes methods for adding, deleting, and notifying observers.

public class Subject {

    //list of watchers
    private Vector vector = new Vector();

    /**
     * add observer
     **/
    public void addObserver(Observer observer){
        vector.add(observer);
    }

    /**
     * delete observer
     **/
    public void deleteObserver(Observer observer){
        vector.remove(observer);
    }

    /**
     * notify all observers
     **/
    public void notifyObserver(String goldenCudgel) {
        for(Observer observer : vector) {
             observer.update(goldenCudgel);
         }
    }

}

Then, we define an observer's interface, containing the "action" after the observer is notified.

public interface Observer {
    void update(String goldenCudgel);
}

At this time, we define the observer entity classes of "Land", "Legend of Thunder", and "Dragon King" respectively to realize specific actions such as thunder and rain.

The realizations of "Lord of Thunder" and "Dragon King" are similar to "Land", so only the observer "Land" is displayed here.

@Component
public class MyGuardianObserver implements Observer {

    @Override
    public void update(String goldenCudgel) {
        if(upGoldenCudgel(goldenCudgel)) {
            System.out.println("The land father appeared");
        }
    }

    public boolean upGoldenCudgel(String goldenCudgel){
        if(Objects.equals(goldenCudgel,"down")){
            return true;
        }
        return false;
    }

}

Then, we can define the specific implementation class "Monkey King" of the observed person.

public class MonkeyKingSubject extends Subject{
    
    /**
     * Is the golden hoop raised or lowered? Haha, guess what. . .
     **/
    public void doGoldenCudgel(String goldenCudgel){
        notifyObserver(goldenCudgel);
    }

}

Finally, let's do a test to see if they can respond to Sun Wukong's notifications.

@PostMapping
public void observerTest(){
    MonkeyKingSubject subject = new MonkeyKingSubject();
    subject.addObserver(new ThunderGodObserver());
    subject.addObserver(new MyGuardianObserver());
    subject.addObserver(new DragonKingObserver());

    subject.doGoldenCudgel("up");
    System.out.println("I am the dividing line----------------------------");
    subject.doGoldenCudgel("down");
}

Results display

Thunderbolt and Thunderbolt
The Dragon King Comes to Rain
I am the dividing line -----------------------------
Landlord appeared

Summarize

How can there be no summary at the end of the story? The observer mode and the event notification mechanism are in a one-to-many relationship. When an object is modified, it will automatically notify the objects that depend on it. The two are independent and decoupled from each other, which saves the need for repeated The resource consumption of the retrieval state can also get the highest feedback speed.

Of course, its shortcomings cannot be ignored:

  1. If an observable object has many direct and indirect observers, it will take a lot of time to notify all observers;
  2. If there is a circular dependency between the observer and the observation target, the observation target will trigger a cyclic call between them, which may cause the system to crash;
  3. The observer pattern does not have a corresponding mechanism to let the observer know how the observed target object has changed, but only know that the observed target has changed;

At the end of the article, the source code is provided as usual, and the background replyeventcan be obtained. That's all for today, if you have a different opinion or betteridea, welcome to contact Ah Q, add Ah Q to join the technical exchange group to participate in the discussion!