Observer mode and event monitoring mechanism

Source: Internet
Author: User

I. Observer Pattern 1.1 Overview

Sometimes referred to as the Publish/subscribe pattern, the Observer pattern defines a one-to-many dependency that allows multiple observer objects to listen to a Subject object at the same time. This subject object notifies all observer objects when the state changes, enabling them to automatically update themselves. It is similar to B/S architecture mode, to build a server side, multiple client display. In fact, this subject object is like a source of information, when the state of the information source sent changes, it will notify all subscribers, so that they do the appropriate processing. In the Baidu Encyclopedia example is, the user interface can act as an observer, the business data is the Observer, the user interface to observe the changes in the business data, the discovery of data changes, is displayed on the interface.

1.2 Participants in the pattern
    • Abstract Theme (Subject): It saves references to all observer objects in a single aggregation, and each subject can have any number of observers. Abstract topics provide an interface that allows you to add and remove observer objects and to notify all observers.
    • Specific topic (CONCRETESUBJECT): The state is deposited into a specific observer object, and all registered observers are notified when the internal state of a specific subject changes.
    • Abstract Observer (Observer): Defines an interface for all specific observers to update themselves when subject notifications are received.
    • Specific observer (Concreteobserver): Implements the update interface required by the abstract observer role in order to align its state with the subject state.

Note :

The information of the observer is derived from the information transmitted by the Notify method in the subject, such as notify (String str) passing the character str information, and the Observer Update (string strobj) receives the STR information and carries out the related operation.

1.3 Applicability

1. When an abstract model has two facets, one aspect depends on the other. The two are encapsulated in separate objects so that they can be individually changed and reused.

2. When a change to an object needs to change other objects at the same time, it is not known how many objects need to be changed.

3. When an object must notify other objects, it cannot assume that other objects are who. In other words, you don't want these objects to be tightly coupled.

1.4 Illustrative examples

Company meeting, the leadership first inform the heads of departments to the conference Room (registration, registration process), in the conference room, everyone is waiting for the leadership of the speech (multiple observers focus on the same subject object), the leader began to say, "This year is half the time, but the performance has not completed the estimated 40% Ah, we have to work" (Notification process), when we heard the leadership of the words, the marketing manager began to speak, "because the whole market is more sluggish in the first half, so the market development is relatively slow, but after the first half of the investigation, we have more important information, the second half, we will certainly expand the market share"; Research and development manager, " Our research and Development Department will continue to work overtime to ensure the completion of the task "(each observer receives notification of the processing process).

Ileader: Abstract Theme (Subject)

 Public Interface Ileader
{
Registration and Registration
 Public void Addmanager (IManager manager);
Remove a registered
 Public void Removemanager (IManager manager);
Notify all Managers
 Public void notifymanagers (String str);
}

Myleader: Specific topics (ConcreteSubject)

 Public class Implements Ileader
{
Store all managers who need to register
Private New Arraylist<imanager> ();
@Override
 Public void Addmanager (IManager Manager)
{
synchronized (this)
{
if NULL &&! (Managerlist.contains (manager)))
{
Managerlist.add (manager);
}
}
}
@Override
 Public void Removemanager (IManager Manager)
{
synchronized (this)
{
if (Managerlist.contains (manager))
{
Managerlist.remove (manager);
}
}
}
@Override
 Public void notifymanagers (String str)
{
 for (IManager imanager:managerlist)
{
Imanager.update (str);
}
}
}

IManager: Abstract Observer (Observer)

 Public Interface IManager
{
/**
* Update
* @param str is consistent with Ileader's notification parameters
*/
 Public void Update (String str);
}

Marketingmanager: Specific observer (CONCRETEOBSERVER)

 Public class Implements IManager
{
@Override
 Public void Update (String str)
{
System.out.print ("");
DoSomething (str);
}
Private void dosomething (String str)
{
if (Str.equals (" effort "))
{
System.out.println ("In the second half of the year, our marketing department will certainly expand more shares ");
}
}
}

Developmanager: Specific observer (CONCRETEOBSERVER)

 Public class Implements IManager
    @Override
     Public void Update (String str)
    {
        System.out.print ("");
        DoSomething (str);
    
    Private void dosomething (String str)
    {
        System.out.println (" Our research and development Department will continue to work overtime to ensure the completion of the Mission");
    }
}

Test class:

 Public class Testmain
{
 Public Static void Main (string[] args)
{
New Myleader ();
New Marketingmanager (); //Marketing Department
New Developmanager (); //Research and Development Department
Registration, registration process
Way One
Leader.addmanager (Marketmanager);
Leader.addmanager (Developmanager);
Way two anonymous: take Engineering department as an example
Leader.addmanager (new IManager ()//Engineering Department
{
@Override
 Public void Update (String str)
{
System.out.print ("");
if (Str.equals (" effort "))
{
DoSomething ();
}
}
Private void dosomething ()
{
System.out.println (" Our engineering department will expedite the implementation of the Project ");
}
});
SYSTEM.OUT.PRINTLN (" Leadership speech: first half of the performance!") ");
Notification process
System.out.println (" send effort Command ");
Leader.notifymanagers (" effort ");
}
}

Output Result:

Leadership speech: First half of the performance!
Send an effort command
The marketing department received the order: in the second half of the year, our marketing department will definitely expand more share
The development department receives the command: Our research and Development Department will continue to work overtime to ensure the completion of the mission
Engineering department received orders: our engineering department will speed up the implementation of the project progress

In practice, for convenience, we are using the second form of registration.

1.5 I push you to pull

The Observer pattern has two versions in the specific implementation of the target (subject) Role and observer role communication.

1) Pull mode: The target role changes, just tell the observer the role of "I changed"; If you want to know the specifics of the change, you'll have to get it from the target role's interface. Pull mode is intended for active confession acquisition.

2) Push mode: Notifies you of a change, and passes the details of the change to the observer role through a parameter. Push mode is the tube you want, first give you.

The use of these two modes depends on the design-time needs of the system. Push mode is appropriate if the target role is more complex and the observer role is updated with some specific information that needs to be changed. If the target role is relatively simple, then pull mode is a good fit.

Second, the event monitoring mechanism

When an action occurs on the event source object, it invokes a method of the event listener and passes the event object past when the method is called.

2.1 Composition Structure

The event listening mechanism in Java consists of three parts: Event source, event object and event listener.

1) Event Source:

A specific event source, for example, if you click on a button, then the button is the event source, you need to register a specific listener if you want the button to respond to certain events.

2) Event object:

Typically inherits from the Java.util.EventObject class, encapsulating the event source object and the information associated with the event. It is passing information between the event source and the event listener.

3) Event Listener (listener):

Implements the Java.util.EventListener interface, which needs to be registered on the event source to be called. It listens for events and handles or forwards events.

However, what is the relationship between the event monitoring mechanism and the observer pattern?

The Observer (Observer) is equivalent to the event listener, the Observer (Observable) or the subject (Subject) is equivalent to the event source and event, and when the logic is executed, the Observer is triggered to trigger the Oberver update, and the observers and parameters can be transmitted.

In fact, the event object in the event mechanism is equivalent to the string parameter object in the notify in the Observer pattern in the previous example.

2.2 Illustrative examples

Doorevent: Event Object

 Public class extends EventObject
{
Private String doorstate = ""; //Indicates the status of the door, there are "open" and "off" two
 Public Doorevent (Object Source)
{
Super (source);
}
 Public void setdoorstate (String doorstate)
{
this. doorstate = Doorstate;
}
 Public String Getdoorstate ()
{
return this. doorstate;
}
}

Idoorlistener: Incident Listener (Event listener)

 Public Interface extends EventListener
{
EventListener is the markup interface that all event listener interfaces must extend, because it is a tag interface with no content,     
    So the event handling method is declared by us as follows:
 Public void dealdoorevent (doorevent event);
}

Frontdoorlistener: Incident Listener (Event listener)

 Public class Implements Idoorlistener
{
/**
* Do a specific opening, closing action
*/
@Override
 Public void dealdoorevent (doorevent event)
{
if (Event.getdoorstate ()! =null && event.getdoorstate (). Equals ("open")
{
System.out.println (" Front door open ");
}
Else
{
System.out.println (" front door closed ");
}
}
}

Doormanager: Event Source

 Public class Doormanager
{
Private New ArrayList ();
 Public void Adddoorlistener (Idoorlistener Listener)
{
synchronized (this)
{
if NULL &&! (Listeners.contains (listener)))
{
Listeners.add (listener);
}
}
}
 Public void Removedoorlistener (Idoorlistener Listener)
{
synchronized (this)
{
if (Listeners.contains (Listener))
{
Listeners.remove (listener);
}
}
}
 Public void notifydoors (doorevent event)
{
 for (Idoorlistener idoorlistener:listeners)
{
Idoorlistener.dealdoorevent (event);
}
}
/**
* Simulated Open Door Event
*/
 Public void fireopend ()
{
if null)
{
return;
}
New Doorevent (this);
Event.setdoorstate ("open");
Notifydoors (event);
}
}

Test class:

 Public class Testmain
{
 Public Static void Main (string[] args)
{
New Doormanager ();
Add Listener
Doormanager.adddoorlistener (new Frontdoorlistener ());
Doormanager.adddoorlistener (new Idoorlistener ()
{
@Override
 Public void dealdoorevent (doorevent event)
{
if null && event.getdoorstate (). Equals ("open"))
{
System.out.println (" open Door, warning light on");
}
Else
{
System.out.println (" rear door closed, warning light off ");
}
}
});
Simulation Events
System.out.println (" Gate Open Event ");
Doormanager.fireopend ();
SYSTEM.OUT.PRINTLN (" Analog door Shutdown Event ");
New Doorevent (Doormanager);
Doorevent.setdoorstate ("close");
Doormanager.notifydoors (doorevent);
}
}

Output Result:

Simulation Door Open Event
Front door open.
The rear door is open and the warning light is lit
Simulating gate shutdown events
Front door closed.
Rear door closed, warning light off

Another example:

button buttons Event listener-Also, observer mode

Reference:

1, http://www.cnblogs.com/wangjq/archive/2012/07/12/2587966.html

2, http://www.cnblogs.com/abcdwxc/archive/2007/09/19/898856.html

3, http://blog.csdn.net/ai92/article/details/375691

4, http://enjiex.iteye.com/blog/1067650

5, http://ericliu1986.iteye.com/blog/629562

6, http://blog.csdn.net/xiaolang85/article/details/5316859

Observer mode and event monitoring mechanism

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.