Friday, 28 February 2014

How To...

Proxy Pattern:
Provides a surrogate or placeholder for another object to control access to it. "Proxy" is actually a repesentative of another object.
A "remote Proxy" controls access to a remote object.
A "virtual Proxy" controls access to a resource that expensive to create.
A "protection Proxy" controls access to a resourse based on access rights.(security)
In this blog I am going to explain first one . This involves RMI ie Remote Method Invocation. This is the one topic in Java , I couldn't get to see, or touch.  Again all information here are referenced from Head First Design Patterns Book.
Image is taken from http://www.oodesign.com/proxy-pattern.html

Suppose client wants to call some methods on a object which is in Server's heap. Server is remote to the client and it has to talk to the server which is on the other side of  the network. RMI stub  act as a client proxy on the client's heap , where as RMI Skeleton act as server proxy on the Server's heap. Mainly these proxies help in serialization (write object in server side, readobject in client side-deserializing, This is before java 2. Now a days we can get proxies dynamically on the go. - just note that Proxies are  different pattern from decorator patterns.)
This needs two sides programming
 1) Client  side program or code  which lookup the RMI registry to get the stub object ,client invokes the method on the stub object, as if the stub is the real service.
       MyInterface service = (MyInterface)Naming.lookup("rmi://127.0.0.1/RemoteHelloworld");
2)Server side programming to give service.
           5 steps for these.
    i) Make a  Remote interface
            a)Extend java.rmi.Remote
              b)Declare that all methods throw a RemoteException.
               c)be sure arguments and return values are primitives or Serializable.
              import java.rmi.*;
                public interface MyRemoteInterface extends Remote {
                  public String helloWorld () throws RemoteException;
                 }
           ii)Make a Remote implementation
                a)Implement the Remote interface
                  b)Extend UnicastRemoteObject
                   c)Write a no-org constructor that declares a RemoteException
                   d)Register Service with the RMI registry
              public class MyImplementation extends UnicastRemoteObject implements MyRemoteInterface {
   public MyImplementation() throws RemoteException {}
      public String helloWorld() {
           return "hello world";
}
//more code
}
In tester in the main method you register the service with the RMI registry
  try {
MyInterface service = new MyImplementation();
Naming.rebind("RemoteHelloworld",service); //  you can give any name to hide your object.
} catch (Exception ex){....}
iii) generate stubs and skeletons
        run rmic on the remote implementation class (not on remote interface)
           %rmic MyImplementation
  iv)run rmiregistry
        bring up a terminal and start the rmiregistry
     %rmiregistry
v)start the service
        bring up another terminal and start your service
%java MyImplementation
 (run the main method of service impementation class)
Suppose I am a client wants to monitor some dogs at remote service. Then,
 First on the server side, we have to make the service available.
To make remote interface:
     import java rmi.*;
    public interface DogRemote extends Remote {
        public int getMicroChipNo() throws RemoteException;
        public String getSpecies() throws RemoteException;
         public String getLocation() throws RemoteExcetion;
         public String getCondition() throws RemoteExeption;
}
If you want to make a method like
public Collar getCollar() throws RemoteException; then you have to make "Collar " Serializable.  Just you can do public class Collar implements Serializable  or extends serializable .(there is no methods to implement).But you have to import java.io.*;   If the class contains any other objects you can make them serializable or declare it as transient.
make remote implementation
import java.rmi.*;
import java.rmi.server.*;
public class Dog extends UnicastRemoteObject implements DogRemote
//instance variable here
public Dog(String location,String species,int microchipno) throws RemoteException{
//code here
}
public int getMicroChipNo() {
    return microchipno;
}
public String getSpecies(){
return species;
}
// all other get codes here
}
Registering with RMI registry
public class DogTester {
   public static void main(String[] args){//you can also input arguments here.
try {
DogRemote pudsy = new Dog("London","poodle", 1234);
Naming.rebind("//"+"London.dogcanal.com" + "/dog",pudsy);/**here you can add differnt locations and different names for objects by passing args if you want.**/
}catch (Exception e){
e.printStackTrace();
}
}
}
Then run rmiregistry followed by the main method of DogTester.
On the client side,
Class to monitor dog and a tester
import java.rmi.*
public class DogMonitor{
  DogRemote pudsy;
public DogMonitor (DogRemote pudsy){
this.pudsy = pudsy;
}
public void dogDetails(){
try
{
      System.out.println("Dog from"+pudsy.getLocation());
     System.out.println("Dog Species"+pudsy.getSpecies());
      System.out.println("Condition"+pudsy.getCondition());
      System.out.println("Microchip number"+getMicroChipNo());
}  catch (RemoteException e){
e.printStackTrace();
     }
   }
}
Write a monitor tester
      import java.rmi.*;
     public class DogMonitorTester{
            public static void main(String[] args){
                  try
                     {
                          DogRemote  pudsy = (DogRemote)Naming.lookup("rmi://London.dogcanal.com/dog");
                          DogMonitor monitor = new DogMonitor(pudsy);
                            }
                              catch (Exception e){
                                    e.printStackTrace();
                             }
                         }
                          monitor.dogDetails();
}
}

       How to monitor dogs( or objects) remotely.             

Comments are welcome. (So that I can correct my mistakes)

Tuesday, 11 February 2014

How To...

Singleton Pattern:
"Ensures a class has only one instance, and provides a global point of access to it."
Here we are making a class , which has only one instance which is instanciated within itself and we never let any other class to make another instance.
we are providing a global access point to the instance. - Head first design pattern.
ex: servelets.
This picture is taken from  http://www.oodesign.com/singleton-pattern.html.

When restricting access , we always have to think about make something a "private". The method which instanciates object is the constructor. So we make constructor "private". When constuctor made private, it should be instanciated in a static method/variable so as to give global access. When you think of global access , make it thread safe.
public class Singleton{
private static Singleton uniqueInstance;
private Singleton(){}
public static synchronized Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
To improve Multitreading
1) Do nothing if the performance of getInstance() is not critical
2)If your application always creates and uses singleton then create Singleton eagerly as JVM creates it when the class is loaded.
       public class Singleton {
          private static Singleton uniqueInstance = new Singleton();
      private Singleton(){}
    public static Singleton getInstance() {
        return uniqueInstance;
    JVM ensures that instance will be created before any thread can access to the static instance variable.
3)Use double-checked locking to reduce the use of sychronization in getInstance() - synchronization kills performance
public class Singleton{
   private volatile static Singleton uniqueInstance;
private Singleton(){}
public static Singleton getInstance(){
if (uniqueInstance == null){  /** only enter the block if it is null. this means it enters synchronized block only once for the first time.**/
synchronized (Singleton.class){
if (uniqueInstance == null)   /** double checking just in case first one checked by  two threads simultaniously  as one of them will succeeds,  other one waits just outside after first checking.**/
   uniqueInstance = new Singleton();
}
}
return uniqueInstance;
}
}
These are all referenced from "Head First Design Patterns" Since I do not want to mess  up with singleton pattern.
Time for our own Singletons. Let us think of Central heating System , and house as a class loader.(one singleton per one class loader). It has only one instance and anybody in the house can have access to it (global) .
I create them eagerly since I bought my house in the winter.(just kidding)

public class HeatingSystem {
private static HeatingSystem uniqueInstance = new HeatingSystem();
private static Temperature ;
//currentTime == calender.getTime();
private HeatingSystem(){}
public static HeatingSystem getInstance(){
return uniqueInstance;
}
public void setTimer(Time startTime, Time endTime){
        if (currentTime.equalsTo( startTime))
            onSystem();
       else if (currentTime .equalsTo(endTime))
            offSystem();
/** to get current time you can use
Calendar calender = Calendar.getInstance();
CurrentTime = calender.getTime();**/

}
public  void setTemp(Temperature temp)
{
        this.Temperature = temp;
}
public void onSytem(){
    // press the button
}
public void offSystem(){
//undo the pressed button
}
}
Now everybody has only one instance , and has global access to that instance. Husband gets the instance switch on the system, He forgets all about it and when he sees the gas bill he could  blame it on the wife since she had the same instance  and access, so he expected her to switched it off as it is her responsibility too.

How to fight over your Gas Bill. (All  characters here are fictitious , if it resembles someone or some incidents then it is purely coincidental).


Friday, 7 February 2014

How To....

The Command Pattern:
"Encapsulates a request as an object, thereby letting you parameterise other objects with different requests queue or log requests and support undoable operations."
It supports the decoupling of the invoker of a request and receiver of the request.
-Head First Design Patterns.
ex: Home automation systems,  ... or where ever you have to press the bottons then think of you as a client and the webpage which holds the button as innocent invoker(he is not responsible for all unexpected actions :))


 This Picture is from:
http://www.oodesign.com/command-pattern.html
 I remembered my dissertation in MSc. Jobs come to the server in a queue, and these jobs are discarded once they are done with it. 
Let us think about Briton got talent.  Let us say "ITV"  is our client. Ant&Deck are (is) our invoker/s. All vendors have different kinds of act to show. Our commands are performing acts.  This is the audition taking place some where in Birmingham  and it is a all day process and people can come anytime between 9am - 5pm and put thier name in the list carried by our invoker (Ant&Deck).  They have nothing to do with who is doing the act. They just have to announce thier name  according to the list and all acts are come as a surprise. Simon Cowell , Alesha Dixon ... undo button invokers.
public interface PerformingAct{
public void perform();
}
public class SingingAct implements PerformingAct{
Team team;
public SingingAct(Team team){
this.team =team;
}
public void perform(){
team.sing();
}
public class StopSingingAct impements PerformingAct{
Team team;
public StopSingingAct(Team team){
this.team =team;
}
public void perform(){
team.retreat();
}
}
Same way we can implement DancingAct, MimingAct,ScreamingAct....and stoping all those acts in a class.
This is our invoker.
public class Invoker{
ArrayList acts;//you can also use a LinkedList or a Queue.
   static PerformingAct stopact;
static int count ==0 ;
public Invoker(){
acts =  new ArrayList();// all invoker may have a list for marking purposes.
}

public void addAct(PerformingAct act){
acts.add(act);
}
public void announce(PerformingAct act){

setStopAct(act);
//check the size of the arraylist here
  PerformingAct act1 = (PerformingAct)acts.remove(0);
act1.perform();
}
public void xbottunPushed(){
count = count+1;
if( count >=2){
stopact.perform();
count ==0;
}
}
public void setStopAct(PerformingAct act){
stopact = act;
}
}
On the day of audition,
public class LoadPerformingActs{
public static void main(String[] args){
Invoker antdeck = new Invoker();
Invoker simon = new Invoker();
Invoker alesha = new Invoker();

Team teamA = new Team();
Team teamB = new Team();
PerformingAct diversity = new DancingAct(teamA);
PerformingAct stopDiversity = new StopDancingAct(teamA);
PerformingAct mindBlowing = new SingingAct(teamB);
PerformingAct stopMindBlowing = new StopSingingAct(teamB);
antdeck.add(diversity);
antdeck.add(mindBlowing);
antdeck.announce(stopDiversity);
simon.xbottonPushed();//this needs thread synchronization
alesha.xbottonPushed();/**this needs thread synchronization in real life. Here we assume that alesha and simon does not push the button at the same time.
.......
continues until 5 pm. **/
}
}
Just have to remember if  you make a class for commands they can be set in a queue and invokers only remember to execute the commands and  all actions are vendors' responsibility. 
  In this way commands helps  Invokers to detach themselves from responsibilities.

How to detach yourself from responsibilities. :>)