Wednesday, December 13, 2017

Observer Pattern

Definition -

    It provides a proxy implementation for another object and controls access to the real object.

These are patterns which you would be using unknowingly (if you are new to design patterns) in the click event listener or the event listeners.
Scenario -

1) Let us have a class called obsrvvalue which will have a variable whose value is being observed. This is called observable.

package ObserverPattern;

import java.util.Observable;

public class obsrvvalue extends Observable {
    
    private int val=0;
    
    public obsrvvalue(int newval) {
        this.val=newval;
    }
    
    public void setnewval(int newval) {
        this.val=newval;
        setChanged();
        notifyObservers();
    }
    
    

}

2) Let us have a class called observerobject which will observe the observable object and check if the value is same or not and report.
package ObserverPattern;

import java.util.Observable;
import java.util.Observer;

public class observerobject implements Observer{
    
    
    private obsrvvalue obs=null;
    
    public observerobject(obsrvvalue o) {
        this.obs=o;
    }

    @Override
    public void update(Observable arg0, Object arg1) {
        if(arg0==arg1) {
            System.out.println("Both are equal");
        }
        else {
            System.out.println("The value is updated");
        }
        
    }

}

3) To see the pattern in demo use the code below

package ObserverPattern;

public class observerdemo {
    
    public static void main(String args[]) {
        
        obsrvvalue o=new obsrvvalue(10);
        observerobject oo= new observerobject(o);
        o.addObserver(oo);
        o.setnewval(10);
    }

}

Place to use -
1) When you have listener waiting to act if the object changes.


The code for the above is present in the link here

No comments:

Post a Comment