Monday, December 11, 2017

Proxy Pattern

Definition -

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

    let us consider an example of Manufacturing of a car in a plant which produces a hatchback and a sedan.
based on the above scenario -
1) We will have an interface called car.

package ProxyPattern;

public interface car {
    
    public void manufacture();

}

2) We will have concrete classes called hatchback and sedan
hatchback.java
 
public class hatchback implements car {

    @Override
    public void manufacture() {
        
        System.out.println("Manufacturing a hatchback");
        
    }

}

sedan.java

package ProxyPattern;

public class sedan implements car {

    @Override
    public void manufacture() {
        
        System.out.println("Manufacturing a sedan");
        
    }

}

3) We will have an handler called carhandler which will be responsible for invoking the classes based on request.
package ProxyPattern;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class carhandler implements InvocationHandler {
    
    public Object realcar=null;
    
    public carhandler(Object realcar) {
        this.realcar=realcar;
    }
    

    @Override
    public Object invoke(Object duplicate, Method arg1, Object[] arg2) throws Throwable {
        
        Object temp=arg1.invoke(realcar, arg2);
        return temp;
    }

}


4) To see the pattern in action use the code below - 
package ProxyPattern;

import java.lang.reflect.Proxy;

public class proxydemo {

    public static void main(String[] args) {
        
        
        car ht=new hatchback();
        carhandler ch=new carhandler(ht);
        car duplicate = (car) Proxy.newProxyInstance(ht.getClass().getClassLoader(),ht.getClass().getInterfaces(),ch);
        
        duplicate.manufacture();

    }

}


Place to use -
1) When the object created is external to the system.
2) Requires access to the original object and in some cases allowing to have modified functionalities.



The code used above can be found in the link here

No comments:

Post a Comment