国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home WeChat Applet WeChat Development Example code for developing WeChat official accounts using the observer pattern in Java design patterns

Example code for developing WeChat official accounts using the observer pattern in Java design patterns

Mar 28, 2017 pm 02:20 PM
java Observer pattern

This article mainly introduces the example of using the Observer Pattern in Java Design Pattern to develop a WeChat public account. The WeChat SDK and other parts of Java will not be detailed here. Only focus on the key parts and the embodiment of the advantages of the observer mode during the development process. Friends in need can refer to

Do you still remember how gangsters cooperate in committing crimes in police movies? When a gang is committing a theft, there are always one or two people standing guard at the door. If there is any sign of trouble, the accomplices inside will be immediately notified to make an emergency retreat. Maybe the person who is cheating doesn’t necessarily know every accomplice inside; and there may be new guys inside who don’t know the one who is cheating. But it doesn't matter. It won't affect the communication between them, because they have already agreed on the secret code.
Haha, the relationship between the watcher and the thief mentioned above is a living example of the observer pattern in reality.

The Observer pattern is also known as the Publish/Subscribe pattern. GOF defines the observer pattern as follows: defines a one-to-many dependency relationship between objects . When the status of an object changes, all objects that depend on it get Notified and updated automatically.
Here let’s talk about an important principle of Object-oriented design - the single responsibility principle. Each object of the system should therefore focus on a discrete abstraction within the problem domain. So ideally, an object does only one thing. This brings many benefits in development: it provides reusability and maintainability, and is also a good basis for reconstruction.
So almost all design patterns are based on this basic Design principle. I think the origin of the observer pattern should be in the processing of GUI and business data, because most of the examples explaining the observer pattern now are on this subject. But the application of the observer pattern is by no means limited to this aspect.


Okay, the understanding of the definition always needs to be analyzed by examples. Today's WeChat service account is quite popular. Let's introduce the observer mode to everyone using the WeChat service account as the background.
Look at a picture:

Example code for developing WeChat official accounts using the observer pattern in Java design patterns

Each user has 3 lines in the above picture, which have been omitted to make the picture clear.
As shown in the picture above, the service account is our subject, and the user is the observer. Now let’s clarify the functions:
1. The service account is the topic, and the business is pushing messages
2. Observers only need to subscribe to the topic, and new messages will be sent
3. When you don’t want this When receiving topic messages, unsubscribe
4. As long as the service account is still there, there will always be people subscribing
Okay, now let’s take a look at the class diagram of the observer pattern:

Example code for developing WeChat official accounts using the observer pattern in Java design patterns

The next step is code time. We simulate a WeChat 3D lottery service account and some subscribers.
First start writing our theme Interface , and observer interface:

package?com.zhy.pattern.observer;?
?
/**?
?*?主題接口,所有的主題必須實(shí)現(xiàn)此接口?
?*?
?*?@author?zhy?
?*?
?*/?
public?interface?Subject?
{?
??/**?
???*?注冊一個觀察著?
???*?
???*?@param?observer?
???*/?
??public?void?registerObserver(Observer?observer);?
?
??/**?
???*?移除一個觀察者?
???*?
???*?@param?observer?
???*/?
??public?void?removeObserver(Observer?observer);?
?
??/**?
???*?通知所有的觀察著?
???*/?
??public?void?notifyObservers();?
?
}?
package?com.zhy.pattern.observer;?
?
/**?
?*?@author?zhy?所有的觀察者需要實(shí)現(xiàn)此接口?
?*/?
public?interface?Observer?
{?
??public?void?update(String?msg);?
?
}

Next, the implementation class of the 3D service account:

package?com.zhy.pattern.observer;?
?
import?java.util.ArrayList;?
import?java.util.List;?
?
public?class?ObjectFor3D?implements?Subject?
{?
??private?List<observer>?observers?=?new?ArrayList<observer>();?
??/**?
???*?3D彩票的號碼?
???*/?
??private?String?msg;?
?
??@Override?
??public?void?registerObserver(Observer?observer)?
??{?
????observers.add(observer);?
??}?
?
??@Override?
??public?void?removeObserver(Observer?observer)?
??{?
????int?index?=?observers.indexOf(observer);?
????if?(index?>=?0)?
????{?
??????observers.remove(index);?
????}?
??}?
?
??@Override?
??public?void?notifyObservers()?
??{?
????for?(Observer?observer?:?observers)?
????{?
??????observer.update(msg);?
????}?
??}?
?
??/**?
???*?主題更新消息?
???*?
???*?@param?msg?
???*/?
??public?void?setMsg(String?msg)?
??{?
????this.msg?=?msg;?
?????
????notifyObservers();?
??}?
?
}</observer></observer>

Simulate two users :

package?com.zhy.pattern.observer;?
?
public?class?Observer1?implements?Observer?
{?
?
??private?Subject?subject;?
?
??public?Observer1(Subject?subject)?
??{?
????this.subject?=?subject;?
????subject.registerObserver(this);?
??}?
?
??@Override?
??public?void?update(String?msg)?
??{?
????System.out.println("observer1?得到?3D?號碼?-->"?+?msg?+?",?我要記下來。");?
??}?
?
}
package?com.zhy.pattern.observer;?
?
public?class?Observer2?implements?Observer?
{?
??private?Subject?subject?;??
???
??public?Observer2(Subject?subject)?
??{?
????this.subject?=?subject?;?
????subject.registerObserver(this);?
??}?
???
??@Override?
??public?void?update(String?msg)?
??{?
????System.out.println("observer2?得到?3D?號碼?-->"?+?msg?+?"我要告訴舍友們。");?
??}?
???
???
?
}

It can be seen that the service account maintains all users who subscribe to messages from it. When there are new messages in the service account, all users are notified. The entire architecture is a loose coupling. The implementation of the theme does not depend on the user. When a new user is added, the code of the theme does not need to be changed; how the user processes the obtained data has nothing to do with the theme;
Finally, take a look at the test code:

package?com.zhy.pattern.observer.test;?
?
import?com.zhy.pattern.observer.ObjectFor3D;?
import?com.zhy.pattern.observer.Observer;?
import?com.zhy.pattern.observer.Observer1;?
import?com.zhy.pattern.observer.Observer2;?
import?com.zhy.pattern.observer.Subject;?
?
public?class?Test?
{?
??public?static?void?main(String[]?args)?
??{?
????//模擬一個3D的服務(wù)號?
????ObjectFor3D?subjectFor3d?=?new?ObjectFor3D();?
????//客戶1?
????Observer?observer1?=?new?Observer1(subjectFor3d);?
????Observer?observer2?=?new?Observer2(subjectFor3d);?
?
????subjectFor3d.setMsg("20140420的3D號碼是:127"?);?
????subjectFor3d.setMsg("20140421的3D號碼是:333"?);?
?????
??}?
}

Output results:

observer1?得到?3D?號碼?-->20140420的3D號碼是:127,?我要記下來。?
observer2?得到?3D?號碼?-->20140420的3D號碼是:127我要告訴舍友們。?
observer1?得到?3D?號碼?-->20140421的3D號碼是:333,?我要記下來。?
observer2?得到?3D?號碼?-->20140421的3D號碼是:333我要告訴舍友們。

There are many places in JDK or Andorid that implement the observer mode, such as XXXView.addXXXListenter, and of course XXXView.setOnXXXListener It is not necessarily the observer mode, because the observer mode is a one-to-many relationship, and setXXXListener is a 1-to-1 relationship and should be called a callback.

恭喜你學(xué)會了觀察者模式,上面的觀察者模式使我們從無到有的寫出,當(dāng)然了java中已經(jīng)幫我們實(shí)現(xiàn)了觀察者模式,借助于java.util.Observable和java.util.Observer。
下面我們使用Java內(nèi)置的類實(shí)現(xiàn)觀察者模式:

首先是一個3D彩票服務(wù)號主題:

package?com.zhy.pattern.observer.java;?
?
import?java.util.Observable;?
?
public?class?SubjectFor3d?extends?Observable?
{?
??private?String?msg?;??
???
???
??public?String?getMsg()?
??{?
????return?msg;?
??}?
?
?
??/**?
???*?主題更新消息?
???*?
???*?@param?msg?
???*/?
??public?void?setMsg(String?msg)?
??{?
????this.msg?=?msg?;?
????setChanged();?
????notifyObservers();?
??}?
}

下面是一個雙色球的服務(wù)號主題:

package?com.zhy.pattern.observer.java;?
?
import?java.util.Observable;?
?
public?class?SubjectForSSQ?extends?Observable?
{?
??private?String?msg?;??
???
???
??public?String?getMsg()?
??{?
????return?msg;?
??}?
?
?
??/**?
???*?主題更新消息?
???*?
???*?@param?msg?
???*/?
??public?void?setMsg(String?msg)?
??{?
????this.msg?=?msg?;?
????setChanged();?
????notifyObservers();?
??}?
}

最后是我們的使用者:

package?com.zhy.pattern.observer.java;?
?
import?java.util.Observable;?
import?java.util.Observer;?
?
public?class?Observer1?implements?Observer?
{?
?
??public?void?registerSubject(Observable?observable)?
??{?
????observable.addObserver(this);?
??}?
?
??@Override?
??public?void?update(Observable?o,?Object?arg)?
??{?
????if?(o?instanceof?SubjectFor3d)?
????{?
??????SubjectFor3d?subjectFor3d?=?(SubjectFor3d)?o;?
??????System.out.println("subjectFor3d's?msg?--?>"?+?subjectFor3d.getMsg());?
????}?
?
????if?(o?instanceof?SubjectForSSQ)?
????{?
??????SubjectForSSQ?subjectForSSQ?=?(SubjectForSSQ)?o;?
??????System.out.println("subjectForSSQ's?msg?--?>"?+?subjectForSSQ.getMsg());?
????}?
??}?
}

看一個測試代碼:

package?com.zhy.pattern.observer.java;?
?
public?class?Test?
{?
??public?static?void?main(String[]?args)?
??{?
????SubjectFor3d?subjectFor3d?=?new?SubjectFor3d()?;?
????SubjectForSSQ?subjectForSSQ?=?new?SubjectForSSQ()?;?
?????
????Observer1?observer1?=?new?Observer1();?
????observer1.registerSubject(subjectFor3d);?
????observer1.registerSubject(subjectForSSQ);?
?????
?????
????subjectFor3d.setMsg("hello?3d'nums?:?110?");?
????subjectForSSQ.setMsg("ssq'nums?:?12,13,31,5,4,3?15");?
?????
??}?
}

測試結(jié)果:

subjectFor3d's?msg?--?>hello?3d'nums?:?110??
subjectForSSQ's?msg?--?>ssq'nums?:?12,13,31,5,4,3?15

可以看出,使用Java內(nèi)置的類實(shí)現(xiàn)觀察者模式,代碼非常簡潔,對了addObserver,removeObserver,notifyObservers都已經(jīng)為我們實(shí)現(xiàn)了,所有可以看出Observable(主題)是一個類,而不是一個接口,基本上書上都對于Java的如此設(shè)計抱有反面的態(tài)度,覺得Java內(nèi)置的觀察者模式,違法了面向接口編程這個原則,但是如果轉(zhuǎn)念想一想,的確你拿一個主題在這寫觀察者模式(我們自己的實(shí)現(xiàn)),接口的思想很好,但是如果現(xiàn)在繼續(xù)添加很多個主題,每個主題的ddObserver,removeObserver,notifyObservers代碼基本都是相同的吧,接口是無法實(shí)現(xiàn)代碼復(fù)用的,而且也沒有辦法使用組合的模式實(shí)現(xiàn)這三個方法的復(fù)用,所以我覺得這里把這三個方法在類中實(shí)現(xiàn)是合理的。

The above is the detailed content of Example code for developing WeChat official accounts using the observer pattern in Java design patterns. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1502
276
How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Understanding Network Ports and Firewalls Understanding Network Ports and Firewalls Aug 01, 2025 am 06:40 AM

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

How does garbage collection work in Java? How does garbage collection work in Java? Aug 02, 2025 pm 01:55 PM

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces

Using HTML `input` Types for User Data Using HTML `input` Types for User Data Aug 03, 2025 am 11:07 AM

Choosing the right HTMLinput type can improve data accuracy, enhance user experience, and improve usability. 1. Select the corresponding input types according to the data type, such as text, email, tel, number and date, which can automatically checksum and adapt to the keyboard; 2. Use HTML5 to add new types such as url, color, range and search, which can provide a more intuitive interaction method; 3. Use placeholder and required attributes to improve the efficiency and accuracy of form filling, but it should be noted that placeholder cannot replace label.

go by example http middleware logging example go by example http middleware logging example Aug 03, 2025 am 11:35 AM

HTTP log middleware in Go can record request methods, paths, client IP and time-consuming. 1. Use http.HandlerFunc to wrap the processor, 2. Record the start time and end time before and after calling next.ServeHTTP, 3. Get the real client IP through r.RemoteAddr and X-Forwarded-For headers, 4. Use log.Printf to output request logs, 5. Apply the middleware to ServeMux to implement global logging. The complete sample code has been verified to run and is suitable for starting a small and medium-sized project. The extension suggestions include capturing status codes, supporting JSON logs and request ID tracking.

Comparing Java Build Tools: Maven vs. Gradle Comparing Java Build Tools: Maven vs. Gradle Aug 03, 2025 pm 01:36 PM

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac

See all articles