package com.youyj.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* 代理类
* @author Administrator
*
*/
class DynamicObj implements InvocationHandler
{
private Object realObj;
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable
{
return method.invoke(realObj, args);
}
public Object getRealObj()
{
return realObj;
}
public void setRealObj(Object realObj)
{
this.realObj = realObj;
}
}
/**
* 目标对象的接口
* @author Administrator
*
*/
interface Car
{
public void start(String type);
public void stop();
}
/**
* 目标对象1
* @author Administrator
*
*/
class Ford implements Car
{
@Override
public void start(String type)
{
System.out.println(type + " 汽车启动了...");
}
@Override
public void stop()
{
System.out.println("Ford 汽车停止了。。。");
}
}
/**
* 目标对象2
* @author Administrator
*
*/
class Benz implements Car
{
@Override
public void start(String type)
{
System.out.println("Benz 汽车启动了...");
}
@Override
public void stop()
{
System.out.println("Benz 汽车停止了。。。");
}
}
public class DynamicProxy
{
/**
* @param args
*/
public static void main(String[] args)
{
DynamicObj dyo = new DynamicObj();
dyo.setRealObj(new Ford());
Car car = (Car) Proxy.newProxyInstance(Car.class.getClassLoader(),
new Class[] { Car.class },
dyo);
car.start("Ford");
}
}