Sunday, December 9, 2012

Design Patterns : Observer Pattern 2

The LoginObservable which has a observers attribute and a currentUsers_ attribute. The former is a list of all the Observers which are registered with the system and the latter is a Map of all the Users currently active on the System.

We also have two flags changed which is essentially indicator of whether the Observable system has changed.
Let us go through the Use case methods first
/**
*
*
*
*/
public IUser login(String userName, char [] password) {
// check pss
changed = true;
IUser user = new User(userName);
if(currentUsers_ == null) {
currentUsers_ = new HashMap();
}
currentUsers_.put(userName, user);
notifyObservers(user);// notify all Observers of this user
return user;
}

Now this method logs the User in. It takes a user name and password creates a
IUser object and then updates both the current User and then the changes
inidicator. The reader can take note of the notifyObservers method
which will be discussed in details later
Somewhat on similar lines the next usecase method is written
/**
*
*
*
*
*/
public IUser logout(String userName, char [] password) {
// check pss
changed = true;
IUser user = null;
if(currentUsers_ != null) {
if(currentUsers_.containsKey(userName)) {
//double check pss
user = currentUsers_.get(userName);
currentUsers_.put(userName, null);
}
}
notifyObservers(user);// notify all Observers of this user
return user;
}


the changed indicator is once again changed the current Users is updated and once
again the notifyObservers method is called.

Next we check on the same method /**
*
*/
@Override
public void notifyObservers(Object arg) {
// TODO Auto-generated method stub
Observer [] observersArray = new Observer[observers.size()];
int count = 0;
for(Observer observer : observers) {
observersArray[count++] = observer;
}

if(this.hasChanged()) {
for(Observer observer : observersArray) {
observer.update(this, arg);
}
}
clearChanged();
observersArray = null;
}
It simply creates an Observer array out of the Observer list and checks
if the Observable has changed .
Then for every element of the array the update method is called.


Finally the clearChanged is called to reset the status to
not changed and the array is freed.

Last we need a Test class and a test script to see the program in action
package org.home.project21.study.designPatterns;

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

public class LoginTester {

/**
* @param args
*/
public static void main(String[] args) {
ILogUser logUser = new LoginObservable(); // want to check who logs in and why
Observer observer = new LoginObserver(); // create an Observer
((Observable)logUser).addObserver(observer); // add it
logUser.login("Alan Stair", "123".toCharArray()); // log in an Observer
logUser.logout("Alan Stair", "123".toCharArray());// log out an Observer
}


}
And the script

javac -sourcepath src -classpath bin -d bin C:\work\workspace\Project21\src\org\home\project21\study\designPatterns\IUser.java
javac -sourcepath src -classpath bin -d bin C:\work\workspace\Project21\src\org\home\project21\study\designPatterns\ILogUser.java
javac -sourcepath src -classpath bin -d bin C:\work\workspace\Project21\src\org\home\project21\study\designPatterns\User.java
javac -sourcepath src -classpath bin -d bin C:\work\workspace\Project21\src\org\home\project21\study\designPatterns\LoginObserver.java
javac -sourcepath src -classpath bin -d bin C:\work\workspace\Project21\src\org\home\project21\study\designPatterns\LoginObservable.java
javac -sourcepath src -classpath bin -d bin C:\work\workspace\Project21\src\org\home\project21\study\designPatterns\LoginTester.java
java -classpath bin org.home.project21.study.designPatterns.LoginTester > ObserverPattern_output.txt
Finally the Output

Observer notes Alan Stair has logged In @ Sun Dec 09 22:34:21 IST 2012 sun.util.calendar.ZoneInfo[id="Asia/Calcutta",offset=19800000,dstSavings=0,useDaylight=false,transitions=6,lastRule=null]
Observer notes Alan Stair has logged In @ Sun Dec 09 22:34:21 IST 2012 sun.util.calendar.ZoneInfo[id="Asia/Calcutta",offset=19800000,dstSavings=0,useDaylight=false,transitions=6,lastRule=null]

Design Patterns : Observer Pattern 1

These days I have been learning design patterns. Since Singleton and Factory are already done to death with, I decided to choose a somewhat obscure one. Observer pattern.

Let's say we have a bean User which implements the below interface


package org.home.project21.study.designPatterns;

/**
 *
 *
 * @author Sanjay
 *
 */
public interface IUser {


    /**
     *
     *
     * @return
     */
    public String getUserName();
}
 
and which is intended to log a user into an interface like something below

package org.home.project21.study.designPatterns;

/**
 *
 *
 * @author Sanjay
 *
 */
public interface ILogUser {

    /**
     *
     *
     *
     * @param userName
     * @param password
     * @return
     */
    public IUser login(String userName, char [] password);
   
    /**
     *
     *
     *
     *
     * @param userName
     * @param password
     * @return
     */
    public IUser logout(String userName, char [] password);
   
    /**
     *
     *
     *
     * @return
     */
    public boolean isLogged(IUser user);
}
 



Now we would like to keep an eye on who logs on to the System. So we decide to create an observable system. Fortunately for us Java has already created a class 
  Observable which can be used for the purpose. For clarity we would extend it. Next we need an Observer class which will intimate us when it notices something 'Observable'. 


package org.home.project21.study.designPatterns;

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

/**
 *
 * This class implements the Observer
 *
 * @author Sanjay
 *
 */
public class LoginObserver implements Observer {

    /**
     *
     *
     */
    @Override
    public void update(Observable arg0, Object arg1) {
        // TODO Auto-generated method stub
        ILogUser loginObservable = (ILogUser) arg0;
        IUser user = (IUser) arg1;
        System.out.println(" Observer notes " + user + " has " + (loginObservable.isLogged(user)?" logged In ":" logged Out ")
                + " @ " + Calendar.getInstance().getTime() + " " + Calendar.getInstance().getTimeZone());
    }

}




The observer class will update the System whenever the update method is invoked.

Now let us turn our attention to the main class The actual Observable. Since it is relatively bigger we would take it chunk by chunk. For completeness below is the source code


package org.home.project21.study.designPatterns;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

/**
 *
 * This class extends the Observable Class
 *
 * @author Sanjay
 *
 */
public class LoginObservable extends Observable implements ILogUser  {
   
    private List observers;
    private Map currentUsers_;
   
    private boolean changed;
   
    public boolean isLogged(IUser user) {
        if(currentUsers_ != null && currentUsers_.containsKey(user.getUserName())) return true;
        else return false;
    }


   
    /**
     *
     *
     *
     */
    public IUser login(String userName, char [] password) {
        // check pss
        changed = true;
        IUser user = new User(userName);
        if(currentUsers_ == null) {
            currentUsers_ = new HashMap();
        }
        currentUsers_.put(userName, user);
        notifyObservers(user);// notify all Observers of this user
        return user;
    }
   
    /**
     *
     *
     *
     *
     */
    public IUser logout(String userName, char [] password) {
        // check pss
        changed = true;
        IUser user = null;
        if(currentUsers_ != null) {
            if(currentUsers_.containsKey(userName)) {
                //double check pss
                user = currentUsers_.get(userName);
                currentUsers_.put(userName, null);
            }
        }
        notifyObservers(user);// notify all Observers of this user
        return user;
    }
   


    /**
     *
     *
     *
     */
    public LoginObservable() {
        // TODO Auto-generated constructor stub
        super();
        observers = new ArrayList();
        changed = false;
    }
   
   
    @Override
    public synchronized void addObserver(Observer o) {
        // TODO Auto-generated method stub
        if(observers != null) {
            observers.add(o);
        }
        else {
            throw new NullPointerException("observers == " + observers);
        }
    }
   
    @Override
    public synchronized int countObservers() {
        // TODO Auto-generated method stub
        if(observers != null) {
            return observers.size();
        }
        else {
            throw new NullPointerException("observers == " + observers);
        }
    }
   
    @Override
    public synchronized void deleteObserver(Observer o) {
        // TODO Auto-generated method stub
        if(observers != null) {
            if(observers.contains(o)) {
                observers.set(observers.indexOf(o), null);
            }
            else {
                throw new IllegalArgumentException( o + " not found in " + observers);
            }
        }
        else {
            throw new NullPointerException("observers == " + observers);
        }
    }
   
    @Override
    public synchronized void deleteObservers() {
        // TODO Auto-generated method stub
        if(observers != null) {
            observers = null;
           
        }       
        observers = new ArrayList();
    }
   
    @Override
    public boolean equals(Object obj) {
        // TODO Auto-generated method stub
        if(obj instanceof LoginObservable) {
            if(((LoginObservable)obj).observers != null && this.observers != null) {
                return this.observers.equals(((LoginObservable)obj).observers);
            }
            else {
                return false;
            }
        }
        return false;
    }
   
    @Override
    public synchronized boolean hasChanged() {
        // TODO Auto-generated method stub
        return changed;
    }
   
    @Override
    public void notifyObservers() {
        // TODO Auto-generated method stub
        this.notifyObservers(null);
    }
   
    @Override
    public void notifyObservers(Object arg) {
        // TODO Auto-generated method stub
        Observer [] observersArray =  new Observer[observers.size()];
        int count = 0;
        for(Observer observer : observers) {
            observersArray[count++] = observer;
        }
       
        if(this.hasChanged()) {
            for(Observer observer : observersArray) {
                observer.update(this, arg);
            }
        }
        clearChanged();
        observersArray = null;
    }
   
    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return " observers " + this.observers.toString();
    }
   
    @Override
    protected synchronized void clearChanged() {
        // TODO Auto-generated method stub
        changed = false;
    }
}
 




Tuesday, March 29, 2011

Strange Point : Is it a turning point or a melting one

Do you ever have the feeling that inspite of all your achievements
and accolades and recognition that you are missing something. that creeping sinking feeling that something may not right at all, that there might be something that has been left empty and worse forgotten. Strangely for some days i have been having this feeling .And it is coming at a high point in my life. I sit and wonder at the karmic chakra of life. I seem to run after the bus, yeah u guessed it right the missed bus even though I know that the next one is coming right now OK may be 5 minutes later.

Monday, March 7, 2011

Life like a banquet laid
comes with all tastes
do not enjoy the main course such
that you dont savour the dessert much

He who lives in a day as first and last
lives a thousand life times in one
He who waits for that mirage of happiness
is dead before his time and gone

The shadows of past may be long
but the sun of the future is bright
Why do u weep for the extra furlong
when the end is in sight

Sunday, August 23, 2009

In Mumbai In Zycus Detailed

In this universe everything moves through God's will. By the grace of the same will I cracked a job in Zycus (a product company ) on 1st August 2009 and joined on 11th of the same month. It was a tough selection process as the Zycus HR's self descriptively called themselves choosy. However through the grace of Lord Ganesha I managed to float across the aptitude, technical written and two technical interviews (one telephonic and the other face to face). They asked a lot of puzzles and technical fine-points form patterns to a basic understanding of the systems.
Finally they asserted that they were happy to take me on board. I moved in with my things in mumbai with abhinav (a close friend) and joined them. Two weeks have passed and as per Lord Ganesha's supreme will everything is working out. Hoping for a long stay at Zycus

In Mumbai In Zycus

In this universe everything moves through GOD's will. By the grace of the same will I cracked a job in Zycus (a product company )

Friday, August 7, 2009

this may be the last post from pune ... what a week it was ... cracked my first freelancing job and also the my second job ... now with me joining mumbai zycus office on tuesday ... it is time to say good bye to pune and also to all my pune friends ... well called them up ... most of them up ... and the rest would get to know by the most famous broadcast of all ... word of mouth ... what say ... lets see and join the next company and see for ourselves what future holds for us ... I guess it is also time to say a temporary good bye to free lancing ... so that I can concentrate on my next job ... enough 4 today ... lets hope my next post ... if from mumbai is full of good news and surprises ... good bye ...