当前位置:网站首页>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 .
边栏推荐
- Radware load balancer common maintenance query commands
- Solve the problem that Base64 compressed files are extracted with spaces after post request
- CTF steganography
- Output type SPED trigger inbound delivery after PGI for inter-company STO's outb
- How do small businesses do a good job in website construction? Is there any guarantee for network companies to build websites
- PVE enables the hardware graphics card pass through function
- Basic DDoS commands
- How to quickly convert stock code into int in quantitative trading?
- CSDN auto sign in
- Salesforce uses hyperlink formula field to implement custom jump
猜你喜欢
Talk to Wu Jiesheng, head of Alibaba cloud storage: my 20 years of data storage (unlimited growth)

Use recursion to form a multi-level directory tree structure, with possibly the most detailed notes of the whole network.

Arm learning (7) symbol table and debugging
![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】如何使用Flutter包和插件

Cross domain and jsonp

Error reported using worker: uncaught domexception: failed to construct 'worker': script at***
![[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
![Graduation project - thesis writing notes [design topic type, thesis writing details, design materials]](/img/66/c0c400609b56dd012d87c620ca66e4.png)
Graduation project - thesis writing notes [design topic type, thesis writing details, design materials]
随机推荐
What is memory out of order access?
2022 postgraduate entrance examination experience sharing [preliminary examination, school selection, re examination, adjustment, school recruitment and social recruitment]
Output type SPED trigger inbound delivery after PGI for inter-company STO's outb
Activity Registration - Tencent cloud digital intelligence driven SME transformation and upgrading series salon · Zhuhai station
What are the selected CDN content acceleration scenarios of Tencent cloud?
Oushudb learning experience sharing (I)
November 20, 2021: the start and end times of a movie can be listed in a small array
What is the website domain name trademark registration process? What is the use of a website domain name trademark?
Basic DDoS commands
CDN access log quality performance monitoring and operation statistical analysis best practices
什么是养老理财?养老理财产品有哪些?
Software cost evaluation: basic knowledge interpretation of cosmoc method
Law / principle / rule / rule / theorem / axiom / essence / Law
Many ministries and commissions strengthened regulation, and Tencent security helped enterprises resist the "mining" Trojan horse
How to select storage space for website construction what factors should be considered in selecting space
Dart series: metaworld pubspec Yaml file details
This invincible design can analyze and operate any mathematical expression
Error reported using worker: uncaught domexception: failed to construct 'worker': script at***
How does smart digital operation get through offline collection and online marketing?
Container JVM that has to be picked up