设计模式复习 之 代理模式

1. Java实现

interface NetWork
{
public abstract void browser();
}
class Real implements NetWork
{
@Override
public void browser() {
// TODO Auto-generated method stub
System.out.println("浏览信息");
}
}
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. 动态代理

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("浏览信息");
}
}
//继承自InvocationHandler Override它的invoke()方法
  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();
}


}

  

posted @ 2011-08-29 00:22  wtx  阅读(194)  评论(0编辑  收藏  举报