Saturday, September 28

Visitor Design pattern in java

                                             Visitor Design pattern in java

Think from a visitors perspective for a while ---

A person comes from US to visit India ... 

Visitor want to visit certain places .. He has the list of places he want to visit . 

So he provide the same list to his travel organizer and ask him to prepare a suitable plan for him to make him travel all the places available in the list.

Organizer takes the list and start contacting his site contact persons . He ask his agents at all places visitor want to visit to accept and welcome the visitor and make him Visit the place. 

So here entire task is divided in to few sub tasks :

1. Visitor -- Ask visitor to plan . Visit the places.
2. Organizer -- activate his place specific agents 
3. Place agents --- Accept the visitor and make him Visit. 





Now lets understand this scenario in Object oriented world of java technology . How design pattern deals with this situation.

As usual , I would be providing all steps involved in the process in system.out.println statements. Code below can be copied as it is and executed in any java environment . System.out,print statements will print all the steps involved in process on console as well


==============================================

Visitor class represents the visitor . He creates the list of places to be visited and invoke schedule method on organizer . Before invoking schedule method Visitor creates instance of Organizer and while constructing instance it uses one argument constructor to initiate Organizer instance with a state having list of Place instances.



package incredibleIndia;

import java.util.ArrayList;
import java.util.List;

public class Visitor implements IVisotor {

    /**
     * @param args
     */
    public static void main(String[] args) {
        List places = new ArrayList();
        places.add(new IndiaGate());
        places.add(new Tajmahal());
        places.add(new BirSujra());
        places.add(new RedFort());
        places.add(new JamaMasjid());
        Organizer org = new Organizer(places);
        System.out
                .println("Visitor ask Organizer to plan for his visit. Visitor provides Organizer the list of places he is interested in ");
        org.schedule(new Visitor());
       
        System.out.println("Visotor Thanks  all .. It wwas wondeful experience... truely incredible India");

    }

    public void visit(IndiaGate india) {
        System.out.println("visitng india gate.....");

    }

    public void visit(Tajmahal india) {
        System.out.println("visitng Tajmahal.....");

    }

    public void visit(BirSujra birSujra) {
        System.out.println("visitng birSujra.....");

    }

    public void visit(RedFort redFort) {
        System.out.println("visitng RedFort....");

    }

    public void visit(JamaMasjid jamaMasjid) {
        System.out.println("visitng JamaMasjid....");

    }

}

This is contract interface which is helping Visitor to visit the places available in the list. Visitor implements this interface and implement are overloaded methods each referring to one single element /place 
interface IVisotor {

    void visit(IndiaGate indiaGate);

    void visit(Tajmahal tajMahal);

    void visit(BirSujra birsujra);

    void visit(RedFort redFort);

    void visit(JamaMasjid jamaMasjid);
}

This is interface for Organizer to implement . It has only schedule method

interface IOrganize {

    public void schedule(IVisotor visitor);

}

Organizer takes the list of places in constructor . In schedule method It iterates over Place instances and invoke their accept method to make the places accept the visitor . in accept() method it passes the Visitor as parameter. Each Place instance being iterated here refer to once actual Place / class implementing Place interface
class Organizer implements IOrganize {
    List places = new ArrayList();

    public Organizer(List places) {
        this.places = places;
    }

    public void schedule(IVisotor visitor) {

        System.out
                .println("Organizer get through the process to initiate the visit and ask place coordinators to welcomes the visitor  ");

        for (Place place : places) {
            place.accept(visitor);
        }

    }

}

Interface for place . Has only one method . Accept . This needs to be implemented by all Place classes
interface Place {

    void accept(IVisotor visitor);

}

One of the class implementing Place interface and defining the logic of accept method . Accept method will accept the visitor and then on visitor instance invoke visit method and pass the current place instance to the visitor . Visitor can use this instance to visit the place 

class IndiaGate implements Place {

    public void accept(IVisotor visitor) {

        System.out.println("IndiaGate accept the visotr and welcomes him");

        System.out.println("IndiaGate visit is started");
        visitor.visit(this);
    }

}


One of the class implementing Place interface and defining the logic of accept method . Accept method will accept the visitor and then on visitor instance invoke visit method and pass the current place instance to the visitor . Visitor can use this instance to visit the place 


class Tajmahal implements Place {

    public void accept(IVisotor visitor) {

        System.out.println("Tajmahal accept the visotr and welcomes him");

        System.out.println("Tajmahal visit is started");
        visitor.visit(this);
    }

}


One of the class implementing Place interface and defining the logic of accept method . Accept method will accept the visitor and then on visitor instance invoke visit method and pass the current place instance to the visitor . Visitor can use this instance to visit the place 


class RedFort implements Place {

    public void accept(IVisotor visitor) {
        System.out.println("RedFort accept the visotr and welcomes him");

        System.out.println("RedFort visit is started");
        visitor.visit(this);
    }

}



-->


One of the class implementing Place interface and defining the logic of accept method . Accept method will accept the visitor and then on visitor instance invoke visit method and pass the current place instance to the visitor . Visitor can use this instance to visit the place 


class JamaMasjid implements Place {

    public void accept(IVisotor visitor) {
        System.out.println("JamaMasjid accept the visotr and welcomes him");

        System.out.println("JamaMasjid visit is started");
        visitor.visit(this);
    }

}


One of the class implementing Place interface and defining the logic of accept method . Accept method will accept the visitor and then on visitor instance invoke visit method and pass the current place instance to the visitor . Visitor can use this instance to visit the place 


class BirSujra implements Place {

    public void accept(IVisotor visitor) {
        System.out.println("BirSujra accept the visotr and welcomes him");

        System.out.println("BirSujra visit is started");

        visitor.visit(this);
    }

}








 Now let us see the output of console
 -------------------------------------------------------------------------------
Visitor ask Organizer to plan for his visit. Visitor provides Organizer the list of places he is interested in 


Organizer get through the process to initiate the visit and ask place coordinators to welcomes the visitor  


IndiaGate accept the visotr and welcomes him
 IndiaGate visit is started

 visiting india gate.....


Tajmahal accept the visotr and welcomes him

Tajmahal visit is started
 visiting Tajmahal.....


BirSujra accept the visotr and welcomes him

BirSujra visit is started
 visitng birSujra.....


RedFort accept the visotr and welcomes him

RedFort visit is started
 visitng RedFort....


JamaMasjid accept the visotr and welcomes him

JamaMasjid visit is started
 visitng JamaMasjid....


Visotor Thanks  all .. It wwas wondeful experience... truly incredible India


Friday, September 27

Java :: Adaptor Design pattern.

                                                          Adaptor Design pattern.




What is Adaptor

Adaptor is used to make tow parties talk with each otherwise could not talk as their communication channel is not compatible with each other

For Example :

Adaptor for a mobile charger : Mobile can not be directly plugged in to electric socket to charge it . It between it requires an adaptor to to get connected. Adaptor converts 220V from electric socket to 9V what Mobile is made to accept .

An interpreter between two people talking two different languages unknown to each other. Interpreter acts as adaptor here.

Let me take you through java code How we can easily implement and use this pattern in java.

A class A has a method m which takes two parameters String ,String But client who wants to invoke that method does not have a pair of strings but has a Map . So how will they talk . We will insert one more class between then which will act as adaptor . It will take input from client ,will covert the Map parameters in String,String pair combinations and will call the class A method m . Thus client and service class A are not talking with each other directly and Adaptor is making their communication possible.

Here is example with java code . I have written are steps in system.out.println statements in methods. Executing then will print all logical steps on console. So copy this code and Execute .


------------------------------------------------------------------------------------------------------








This is the client class which has a Map with it But want to invoke execute of service class which expects a pair of String. So it can't call Service class directly Instead it invokes execute method in Adaptor class



package adaptor;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class Client {

    /**
     * @param args
     */
    public static void main(String[] args) {

        IAdaptor adaptor = new Adaptor();
        Map map = new LinkedHashMap();
        map.put("Client", "Calling adaptor");
        map.put("adaptor", "redirecting request to service");
        map.put("service", "returning results to adaptor");
        map.put("then adaptor", "returns result to Client");
        map.put("Client and", "adaptor are compatible");
        map.put("Client has", "HashMap ,Service execute() method expects String ,String parameters");
        map.put("so client", "is incompatible to call service directly");
        map.put("adaptor has",
                "execute() method parameters as HashMap , So makes client compatible to call adaptor");
        map.put("further adaptor",
                "transform the input parameter and covert it in format as expected by service");
        map.put("thus", "Client execute service execute() method with the intervention of adaptor");
        map.put("adator class", "Acts as adaptor here to make Client call Service.");
        adaptor.execute(map);

    }

}

Interface For Adaptor Class that defines the execute method signature
interface IAdaptor {

    void execute(Map map);
}

Adaptor Class . It takes parameter from client ,transform the input in parameters expected by service class and then execute service class method
class Adaptor implements IAdaptor {
    IService service;

    public void execute(Map map) {
        service = new Service();

        Set set = map.entrySet();
       
        System.out.println("let us print all key value pairs");
        System.out.println("=======================================");

        for (Object object : set) {

           Entry entry=(Entry)object;

            service.execute(entry.getKey().toString(), entry.getValue().toString());

        }

    }
}

Interface for service class
interface IService {
    public void execute(String key, String value);
}

Service class .It has the acutal method that execute the required logic and It expects the parameter as String,String
class Service implements IService {

    public void execute(String key, String value) {
       
        System.out.println(  key + "--->  " + value);

    }

}





-->


Let Us see the output now
=======================================
Client--->  Calling adaptor


adaptor--->  redirecting request to service


service--->  returning results to adaptor


then adaptor--->  returns result to Client


Client and--->  adaptor are compatible


Client has--->  HashMap ,Service execute() method expects String ,String parameters


so client--->  is incompatible to call service directly


adaptor has--->  execute() method parameters as HashMap , So makes client compatible to call adaptor


further adaptor--->  transform the input parameter and covert it in format as expected by service


thus--->  Client execute service execute() method with the intervention of adaptor


adator class--->  Acts as adaptor here to make Client call Service.


Thursday, September 26

Proxy Design Pattern in Java, lazy loading using Proxy Design Pattern

                         Proxy Design Pattern in Java, lazy loading using Proxy Design Pattern

What is Proxy Design Pattern 

1. Proxy design patten works on the principal of exposing an Java Instance through a proxy instead of actual object. 

2. Client would never know anything about actual object and through Proxy only relevant behavior of actual object will be exposed to client.

3. Proxy Pattern can be used for applying security on actual Object. Service provider does not want actual class to be visible to any client Instead It would be shared as per Client contract agreement . Service provider may agree to share only a part of Service with it's client and for that It may expose a different contract in the form of interface in java . 





-->


4. This concept is very useful for lazily loading an instance . Data will be loaded only when it is actually required in an operation . Till then only proxy to Real instance will be kept as reference So as to invoke desired method later and retrieve the actual instance. 

I have tried to cover both these things directly through Java Code. 

Which class is doing what is directly written in System.out.println statement in each Class below . Executing the code will print all description on console.


Example 1.

This example covers How we can secure premium part of our Service from public cliewnts

public class ProxyClient {

    /**
     * @param args
     */
    public static void main(String[] args) {
        ServiceProxy proxy = new ServiceProxy();
        System.out.println("Clients invokes the operation on ServiceProxy instance....");
        System.out
                .println("Here Client is invoking operation on Proxy Service only. It knows nothing about actual service. Thus using proxy of actual object");
        proxy.operate();
    }

}

class RealService implements IService {

    RealService() {

        System.out
                .println("Service Provider never wish to share the instance of this class to any client publicly as it contains some premium methods as well which are just for premium clients. So it wants to restrict the access of premium methods publicly");
    }

    public void operate() {
        System.out.println("this is the real operation where actual logic is executed......");
        System.out
                .println("This is a premium method . It should not be shared publicly. It is not exposed  through IService interface");
    }

    public void execute() {
        System.out
                .println("This is a premium method . It should not be shared publicly. It is not exposed  through IService interface");

    }

    public void serve() {
        System.out
                .println("This is a premium method . It should not be shared publicly. It is not exposed  through IService interface");

    }

}

// This is the contract which can be publicly shared to all the clients to access methods available for all public
interface IService {

    public void operate();
}

class ServiceProxy implements IService {

    ServiceProxy() {

        System.out
                .println("Service provider does not want to expose actual instance of RealService publicly to everyone. It will share that only with premium clients.So an proxy is created . This Proxy implement the all methods of interface that actual service implements. Now this proxy is available to all the client to invoke public method without even knowing about the actual instance");
    }

    public void operate() {

        System.out.println("Here proxyService is delegating the call to Actual service method....");
        System.out
                .println("Here call is delegated to actual service and actual logic is executed in actual service method only . Result returned from that is received in proxy instance and is sent back to client.This Client remains totally agnostic of Actual service and Just deal with Proxy Service to invoke operations available in real service.");
        IService service = new RealService();
        service.operate();
    }

}



This example will print on console :




---------------------------
 It is Just proxy of actual object. So on instantiation is created just empty object. Data will be lazily loaded on invocation of operate() method
Clients invokes the operation on ServiceProxy instance....
Here Client is invoking operation on Proxy Service only. It knows nothing about actual service. Thus using proxy of actual object
Here proxyService is delegating the call to Actual service method....
Here call is delegated to actual service and actual logic is executed in actual service method only . Result returned from that is received in proxy instance and is sent back to client.This Client remains totally agnostic of Actual service and Just deal with Proxy Service to invoke operations available in real service.
Actual Instance is created here. It execute database calls and provide a state to the Object

--------------------------- 


Example 2

This example covers how lazy loading works and implemented using Proxy Design Pattern 


package pkg;

public class Client {
    IService proxy;

    Client() {
        System.out
                .println("Here When instance is created it only associates the proxy with it. Proxy instance is created. But Actual Service is not constructed ");
        proxy = new ServiceProxy();
    }

    /**
     * @param args
     */
    public void invoker() {

        System.out
                .println("On invocation of operate() method on proxy real instance is created. So instance of stateful object is created only when it is actually required. Till that time client only keeps the proxy to actual object. This is the concept of lazy loading which is heavily used in lot of J2ee frameworks like Spring");
        proxy.operate();
    }

    public static void main(String args[]) {
        Client client = new Client();
        client.invoker();
    }

}

class RealService implements IService {
    DBObject object;

    RealService() {
        System.out
                .println("Actual Instance is created here. It execute database calls and provide a state to the Object");
        object = new DBObject();

        // JDBC Code is executed to provide a state to object.

    }

    public void operate() {
        // TODO Auto-generated method stub
        object.decorateObject();
    }

}

// This interface has no method but is very useful in implementing Lazy loading concept
interface IService {

    void operate();

}

class ServiceProxy implements IService {

    ServiceProxy() {

        System.out
                .println("It is Just proxy of actual object. So on instantiation is created just empty object. Data will be lazily loaded on invocation of operate() method");
    }

    public void operate() {

        System.out.println("Here proxyService is delegating the call to Actual service method....");
        System.out
                .println("Here call is delegated to actual service and actual logic is executed in actual service method only . Result returned from that is received in proxy instance and is sent back to client.This Client remains totally agnostic of Actual service and Just deal with Proxy Service to invoke operations available in real service.");
        IService service = new RealService();

    }

}

class DBObject {

    public void decorateObject() {

        System.out.println("data is fetched from DB to apply other attributes to the object");
    }

}

This example will print on console :

---------------------------
Here When instance is created it only associates the proxy with it. Proxy instance is created. But Actual Service is not constructed
It is Just proxy of actual object. So on instantiation is created just empty object. Data will be lazily loaded on invocation of operate() method
On invocation of operate() method on proxy real instance is created. So instance of stateful object is created only when it is actually required. Till that time client only keeps the proxy to actual object. This is the concept of lazy loading which is heavily used in lot of J2ee frameworks like Spring
Here proxyService is delegating the call to Actual service method....
Here call is delegated to actual service and actual logic is executed in actual service method only . Result returned from that is received in proxy instance and is sent back to client.This Client remains totally agnostic of Actual service and Just deal with Proxy Service to invoke operations available in real service.
Actual Instance is created here. It execute database calls and provide a state to the Object
---------------------------