Java Program Performance Optimization reading notes (vi) design pattern: Observer mode __java

Source: Internet
Author: User
I. Observer model

The Observer pattern defines a One-to-many dependency between objects so that whenever an object changes state, all objects that depend on it are notified and automatically updated . It separated the observer from the object of the Observer. Improves the maintainability and reusability of the application. The Observer pattern is also known as the Publish/subscribe (Publish/subscribe) pattern .

application scenario for observer mode :

1. Updates to an object's state require that other objects be synchronized with updates , and that the number of other objects is dynamically variable.

2. Objects only need to notify their updates to other objects without having to know the details of other objects.

the advantages of the Observer model :

1, subject and observer are loosely coupled , respectively, can be independently changed.

2, subject in the broadcast notice, do not need to specify a specific observer, observer can decide whether to subscribe to the subject notice.

3, adhere to most grasp principles and common design principles, high cohesion, low coupling .

defect of observer pattern :

1, loose coupling causes the code relationship is not obvious, sometimes may be difficult to understand.

2. If a subject is subscribed to by a large number of observer, there may be an efficiency problem when broadcasting notifications. Ii. The realization of the Observer model

There are many forms of implementing the observer pattern, one being the form of "Registration---notice---revocation".

1. Observer Observer: All potential observers must implement the observer interface, which has only the update method, which is invoked when the theme changes.

Public interface Observer
    void update (float temprature);

2. specific observer Concreteobserver: A specific observer can be any class that implements the Observer interface. The observer must register a specific topic and receive updates.

public class Concreteobserver implements Observer
    private float temperature;
    Private final Subject Subject;

    Public Concreteobserver (Final Subject Subject)
        this.subject = Subject;
        This.subject.registerObserver (this);

    public float gettemperature ()

    public void Settemperature (final float temperature)
        this.temperature = temperature;

    @Override public
    void update (final float temperature)
        this.temperature = temperature;

3. Observer subject: The subject interface, the Observer observable, the object registers with this interface as the Observer , or deletes itself from the observer, each subject can have multiple observers.

Public interface Subject
    void Registerobserver (Observer o);

    public void Removeobserver (Observer o);

    public void Notifyobservers ();


4.  specifically observable ConcreteSubject : A specific theme implements the theme interface, and in addition to registration and revocation, specific topics are also implemented Notifyobservers The () method, which is used to update all observers when the theme state changes. Specific topics may also have methods for setting up and getting states.

public class ConcreteSubject implements Subject {private final list<observer> observers;

    private float temperature;
    public float gettemperature () {return temperature;
    private void Temperaturechanged () {this.notifyobservers ();
        } public void Settemperature (final float temperature) {this.temperature = temperature;
    This.temperaturechanged ();
    Public ConcreteSubject () {observers = new arraylist<observer> ();
    @Override public void Registerobserver (Final Observer o) {observers.add (o);
        @Override public void Removeobserver (Final Observer o) {if (Observers.indexof (o) >= 0)
        {Observers.remove (o);
            @Override public void Notifyobservers () {for final Observer o:observers) {
        O.update (temperature); }

The client uses the following code:

public class Client
    static void Main (final string[] args)
        final concretesubject sb = new Concre Tesubject ();
        Sb.settemperature ((float) 20.00);

        Final Observer o = new Concreteobserver (SB);
        Sb.settemperature ((float) 21.00);

third, JDK observable

The Java.util package contains basic Observer interfaces and observable abstract classes. Functionally, it is similar to the subject interface and the Observer interface. However, it is much more convenient to use, because many functions, such as registering, deleting, notifying the observer, have been built in. Commonly used controls, such as JButton in swing programming, are implemented in observer mode.

The processing code for the button:

JButton btn = new JButton ();  
        Btn.addactionlistener (new ActionListener () {  
            @Override public  
            void actionperformed (ActionEvent e) {  
                // TODO auto-generated Method Stub  
                //Here do event handling  
Add Code for button:
public static void Main (string[] args) {
	JFrame p = new JFrame ();
	JButton btn = new JButton ("click Me");
	Btn.addactionlistener (New Btnlistener ());
	P.add (BTN);
	P.pack ();
	P.setvisible (TRUE);	
Iv. Push and pull

The "push" means that the subject maintains a list of the observers, and whenever updates occur,subject pushes the update message to the Observer .

The way to "pull" means that each observer maintains a list of the subject they care about, and decides to subject get the updated data at the right time.

The benefits of "push" include :

1, High efficiency . If no updates occur, there will be no action to update the message push, meaning that every time a message push occurs after an actual update event.

2, real-time . The notification action can be triggered the first time after an event occurs.

3, can be established by the subject notice time, can avoid some busy time .

4, can express the sequence of different events occurred .

The benefits of "pull" include :

1, if many observers, subject to maintain the list of subscribers, may be difficult, or bloated, the subscription relationship to observer to complete.

2, observer can ignore it does not care about the change events , just to get their interest in the event can be.

3, observer can determine the time to get update events .

4, pull the form can let subject better control each observer each query update access rights .

Related Article

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: 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.