public interface Dog
{
//info方法声明
public void info();
//run方法声明
public void run();
}
public class GunDog implements Dog
{
//info方法实现,仅仅打印一个字符串
public void info()
{
System.out.println("我是一只猎狗");
}
//run方法实现,仅仅打印一个字符串
public void run()
{
System.out.println("我奔跑迅速");
}
}
public class TxUtil
{
//第一个拦截器方法:模拟事务开始
public void beginTx()
{
System.out.println("=====模拟开始事务=====");
}
//第二个拦截器方法:模拟事务结束
public void endTx()
{
System.out.println("=====模拟结束事务=====");
}
}
public class MyInvokationHandler implements InvocationHandler
{
//需要被代理的对象
private Object target;
public void setTarget(Object target)
{
this.target = target;
}
//执行动态代理对象的所有方法时,都会被替换成执行如下的invoke方法
public Object invoke(Object proxy, Method method, Object[] args)
throws Exception
{
TxUtil tx = new TxUtil();
//执行TxUtil对象中的beginTx。
tx.beginTx();
//以target作为主调来执行method方法
Object result = method.invoke(target , args);
//执行TxUtil对象中的endTx。
tx.endTx();
return result;
}
}
public class MyProxyFactory
{
//为指定target生成动态代理对象
public static Object getProxy(Object target)
throws Exception
{
//创建一个MyInvokationHandler对象
MyInvokationHandler handler = new MyInvokationHandler();
//为MyInvokationHandler设置target对象
handler.setTarget(target);
//创建、并返回一个动态代理,返回一个指定接口的代理类实例,该接口可以将方法调用指派到指定的调用处理程序
return Proxy.newProxyInstance(target.getClass().getClassLoader()
, target.getClass().getInterfaces(), handler);
}
}
public class Test
{
public static void main(String[] args)
throws Exception
{
//创建一个原始的GunDog对象,作为target
Dog target = new GunDog();
//以指定的target来创建动态代理
Dog dog = (Dog)MyProxyFactory.getProxy(target);
//调用代理对象的info()和run()方法
dog.info();
dog.run();
}
}
图片代理模式:
public interface Image
{
void show();
}
//使用该BigImage模拟一个很大图片
public class BigImage implements Image
{
public BigImage()
{
try
{
//程序暂停3s模式模拟系统开销
Thread.sleep(3000);
System.out.println("图片装载成功...");
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
}
//实现Image里的show()方法
public void show()
{
System.out.println("绘制实际的大图片");
}
}
public class ImageProxy implements Image
{
//组合一个image实例,作为被代理的对象
private Image image;
//使用抽象实体来初始化代理对象
public ImageProxy(Image image)
{
this.image = image;
}
/**
* 重写Image接口的show()方法
* 该方法用于控制对被代理对象的访问,
* 并根据需要负责创建和删除被代理对象
*/
public void show()
{
//只有当真正需要调用image的show方法时才创建被代理对象
if (image == null)
{
image = new BigImage();
}
image.show();
}
}
public class BigImageTest
{
public static void main(String[] args)
{
long start = System.currentTimeMillis();
//程序返回一个Image对象,该对象只是BigImage的代理对象
Image image = new ImageProxy(null);
System.out.println("系统得到Image对象的时间开销:" +
(System.currentTimeMillis() - start));
//只有当实际调用image代理的show()方法时,程序才会真正创建被代理对象。
image.show();
}
}