Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Comparative Analysis of Observer Mode and delegation in Java

2025-04-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces "the comparative analysis of the observer mode and the entrusted example in the Java". In the daily operation, I believe that many people have doubts on the comparative analysis of the observer mode and the entrusted example in the Java. The editor consulted all kinds of data and sorted out a simple and useful method of operation. I hope it will be helpful for everyone to answer the doubt of "the comparative analysis of the observer mode and the entrusted example in Java". Next, please follow the editor to study!

Code background

A class, there are two types of students, A: do not study, play, but play different things, some play games, some watch TV

Category B: students on guard, specially watching the teacher's movements. If the teacher enters the class, he will inform everyone immediately.

In this way, there is a need for the sentry students to inform all the students who play: the teacher is coming, and different students have different reactions, some turn off the TV immediately, and some stop playing games.

Introduction to the Observer Model

Observer pattern: defines an one-to-many dependency that allows multiple observer objects to listen to a subject object at the same time.

When the state of the subject object changes, it notifies all observer objects so that they can update themselves automatically.

The main solution: the problem of notifying other objects of a change in the state of one object, and taking into account easy to use and low coupling to ensure a high degree of cooperation.

When to use: when the state of an object (target object) changes, all dependent objects (observer objects) will be notified for broadcast notification.

How to solve it: using object-oriented technology, you can weaken this dependency.

Key code: there is an ArrayList in the abstract class for observers.

Realize

Observer (student) / * abstract observer * * @ author Promsing (Zhang Youbo) * @ version 1.0.0 * @ since 2022-5-10-15:32 * / public interface Observer {public abstract void updateState () } / * specific observer * * @ author Promsing (Zhang Youbo) * @ version 1.0.0 * @ since 2022-5-10-15:39 * / public class ConcreteObserver implements Observer {/ / the name of the observer private String name; / / the status of the observer private String observerState; / / clearly specific notifier private ConcreteSubject subject / / get set method omits public ConcreteObserver (String name, ConcreteSubject subject) {this.name = name; this.subject = subject;} @ Override public void updateState () {observerState=subject.getSubjectState (); System.out.println (name+ "playing games"); String str=String.format ("Observer% s: new state is% s", name,observerState); System.out.println (str) }} / * * specific observer * * @ author Promsing (Zhang Youbo) * @ version 1.0.0 * @ since 2022-5-10-15:39 * / public class ConcreteObserver2 implements Observer {/ / the name of the observer private String name; / / the status of the observer private String observerState; / / clearly specific notifier private ConcreteSubject subject / / get set method omits public ConcreteObserver2 (String name, ConcreteSubject subject) {this.name = name; this.subject = subject;} @ Override public void updateState () {observerState=subject.getSubjectState (); System.out.println (name+ "watching TV"); String str=String.format ("Observer% s: new state is% s", name,observerState); System.out.println (str) } Notifier (teacher) / * * Abstract Notifier * * @ author Promsing (Zhang Youbo) * @ version 1.0.0 * @ since 2022-5-10-15:30 * / public abstract class Subject {/ / manage the collection of observers private List observers=new ArrayList (); / / add Observer public void add (Observer observer) {observers.add (observer) } / / reduce observer public void detach (Observer observer) {observers.remove (observer);} / * notify all observers * / public void notifyMsg () {for (Observer observer: observers) {observer.updateState () } / * specific notifier * * @ author Promsing (Zhang Youbo) * @ version 1.0.0 * @ since 2022-5-10-15:38 * / public class ConcreteSubject extends Subject {/ / notifier's status private String subjectState; / / get set method public String getSubjectState () {return subjectState;} public void setSubjectState (String subjectState) {this.subjectState = subjectState }} Main method / * * console Main method * * @ author Promsing (Zhang Youbo) * @ version 1.0.0 * @ since 2022-5-10-15:48 * / public class MainTest {public static void main (String [] args) {/ / create a topic / notifier ConcreteSubject subject=new ConcreteSubject () / / new out observer (student) ConcreteObserver studentZhang = new ConcreteObserver ("Xiao Zhang", subject); ConcreteObserver studentLiu = new ConcreteObserver ("Xiao Liu, subject); ConcreteObserver studentWang = new ConcreteObserver (" Xiao Wang, subject "); / / add the observer to the notification queue subject.add (studentZhang); subject.add (studentLiu); subject.add (studentWang) / / notifier (teacher) status change, inform each student subject.setSubjectState ("teacher is back, I want to study hard"); subject.notifyMsg (); System.out.println ("-");}}

Entrustment introduction

Delegate can be regarded as the abstraction of the function and the "class" of the function. The instance of the delegate will represent a specific function

A delegate can carry multiple methods, all of which are called up in turn. You can make the methods carried by the delegate object do not need to belong to the same class.

The delegated event model can be defined by three components: events, event sources, and event listeners.

Simply speaking, the implementation of delegation is implemented by reflection.

Realize

Observers / * listeners / observers play games * event listeners * @ author Promsing (Zhang Youbo) * @ version 1.0.0 * @ since 2022-5-8-11:17 * / public class PlayingGameListener {public PlayingGameListener () {System.out.println ("I am playing game start time" + new Date ()) } public void stopPlayingGame (Date date) {System.out.println ("teacher is coming, hurry back to your seat, end time" + date) }} / * listener / Observer watching TV * event listener * @ author Promsing (Zhang Youbo) * @ version 1.0.0 * @ since 2022-5-8-11:17 * / public class WatchingTVListener {public WatchingTVListener () {System.out.println ("I am watching TV" + new Date ()) } public void stopWatchingTV (Date date) {System.out.println ("here comes the teacher, turn off the TV." End time "+ date);} abstract event source of notifier / * * notifier * @ author Promsing (Zhang Youbo) * @ version 1.0.0 * @ since 2022-5-8-11:15 * / public abstract class Notifier {/ / each notifier has a queue (notification: objects, methods, parameters) private EventHandler eventHandler=new EventHandler () Public EventHandler getEventHandler () {return eventHandler;} public void setEventHandler (EventHandler eventHandler) {this.eventHandler = eventHandler;} / / increase the number of students who need help with the lookout public abstract void addListener (Object object,String methodName,Object...args); / / tell all the students who need to help with the lookout: the teacher is coming public abstract void notifyX () } / * * Notifier subcategory, Sentinel * event Source * @ author Promsing (Zhang Youbo) * @ version 1.0.0 * @ since 2022-5-8-11:15 * / public class GoodNotifier extends Notifier {@ Override public void addListener (Object object, String methodName, Object...args) {System.out.println ("A new classmate entrusts a conscientious watchman!") This.getEventHandler () .addEvent (object, methodName, args);} @ Override public void notifyX () {System.out.println ("the conscientious watchman tells all students in need that the teacher is here"); try {/ / Optimization: asynchronously notify this.getEventHandler (). NotifyX ();} catch (Exception e) {e.printStackTrace () The event class abstracted from the event / * can also be called the method class * event * @ author Promsing (Zhang Youbo) * @ version 1.0.0 * @ since 2022-5-8-11:03 * / public class Event {/ / the object private Object object; / / the name of the method to be executed private String methodName / / parameters to execute the method private Object [] params; / / the parameter type private Class [] paramTypes; / / several setter getter public Object getObject () {return object;} public String getMethodName () {return methodName;} public void setMethodName (String methodName) {this.methodName = methodName;} public Object [] getParams () {return params } public void setParams (Object [] params) {this.params= params;} public Class [] getParamTypes () {return paramTypes;} public void setParamTypes (Class [] paramTypes) {this.paramTypes = paramTypes;} public Event () {} public Event (Object object,String methodName,Object...args) {this.object=object; this.methodName=methodName; this.params=args ContractParamTypes (this.params);} / generate a parameter type array private void contractParamTypes (Object [] params) {this.paramTypes=new Class [params.length]; for (int iArray) based on the parameter array

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 288

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report