1. Java implementation
Interface Network
{
Public abstract void browser ();
}
Class real implements network
{
@ Override
Public void browser (){
// Todo auto-generated method stub
System. Out. println ("browsing information ");
}
}
Public class designpattern_proxy implements network {
Private Network newwork;
Designpattern_proxy (network Network)
{
This. newwork = network;
}
@ Override
Public void browser (){
// Todo auto-generated method stub
This. newwork. browser ();
}
Public static void main (string [] ARGs)
{
New designpattern_proxy (New Real (). browser ();
}
}
2. Dynamic proxy
Import java. Lang. Reflect. invocationhandler;
Import java. Lang. Reflect. method;
Import java. Lang. Reflect. proxy;
Interface Network
{
Public abstract void browser ();
}
Class real implements network
{
@ Override
Public void browser (){
// Todo auto-generated method stub
System. Out. println ("browsing information ");
}
}
// Inherit from invocationhandler override its invoke () method
public class designpattern_dynmicproxy implements InvocationHandler{
private Object sub;
public designpattern_dynmicproxy(){}
public designpattern_dynmicproxy(Object obj)
{
this.sub = obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
System.out.println("before calling " + method);
method.invoke(sub, args);
System.out.println("after calling " + method);
return null;
}
public static void main(String [] args)
{
Real r = new Real();
InvocationHandler ds = new designpattern_dynmicproxy(r);
Class cls = r.getClass();
NetWork nw = (NetWork)Proxy.newProxyInstance(cls.getClassLoader(), cls.getInterfaces(),ds);
nw.browser();
}
}