当前位置:网站首页>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 .
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 .
边栏推荐
- Mobile direct payment, super convenient
- Echo framework: automatically add requestid
- . Net core cross platform development bbs forum (connotation source code + complete operation video)
- [planting grass by technology] 13 years' record of the prince of wool collecting on the cloud moving to Tencent cloud
- Solve the problem that Base64 compressed files are extracted with spaces after post request
- CSDN auto sign in
- PVE enables the hardware graphics card pass through function
- Radware load balancer common maintenance query commands
- The Mars rescue plan has been released. The year of the tiger is limited to dolls waiting for you!
- A review of Tencent digital ecology conference · wechat low code special session
猜你喜欢

Cross domain and jsonp

Zhongshanshan: engineers after being blasted will take off | ONEFLOW u

【Flutter】如何使用Flutter包和插件
Talk to Wu Jiesheng, head of Alibaba cloud storage: my 20 years of data storage (unlimited growth)

Arm learning (7) symbol table and debugging
Shengdun technology joined dragon lizard community to build a new open source ecosystem

JS input / output statements, variables
![2022 postgraduate entrance examination experience sharing [preliminary examination, school selection, re examination, adjustment, school recruitment and social recruitment]](/img/05/e204f526e2f3e90ed9a7ad0361a72e.png)
2022 postgraduate entrance examination experience sharing [preliminary examination, school selection, re examination, adjustment, school recruitment and social recruitment]
![[flutter] comment utiliser les paquets et plug - ins flutter](/img/a6/e494dcdb2d3830b6d6c24d0ee05af2.png)
[flutter] comment utiliser les paquets et plug - ins flutter

LMS Virtual. Derivation method of lab acoustic simulation results
随机推荐
[technical grass planting] take you to Tencent cloud's private cloud disk in ten minutes
SAP executes PGI on the delivery order of STO and reports an error -fld selectn for Mvmt type 643 acct 400020 differences
Software cost evaluation: basic knowledge interpretation of cosmoc method
Tencent cloud recruitment order sincerely invites ISV partners for customized development!
PHP implementation of interval sorting of classified data
How is the national standard easygbs video technology applied in the comprehensive supervision scenario of the power supply business hall?
How to learn website construction does website construction need code
[technical grass planting] deploy a super large capacity and unlimited speed network disk in Tencent cloud
Remove the cloud disk service display "continued" logo
Part of the problem solution of unctf2020
How to build a pagoda panel web site on Tencent ECS?
November 17, 2021: the longest path of the same value. Given a binary tree, find the longest path
Leetcode lecture on algorithm interview for large factories 2 Time space complexity
On November 11, 2021, live broadcast e-commerce opened a new way to play
Echo framework: implementing distributed log tracing
Why traifik ingress?
Container JVM that has to be picked up
Kubernetes' ci/cd practice based on Jenkins spinnaker - adding product image scanning
Use recursion to form a multi-level directory tree structure, with possibly the most detailed notes of the whole network.
Network security meets new regulations again, UK and US warn apt hacker attacks November 18 global network security hotspots