静态代理
package com.zzh.test;
/**
* 静态代理 代理类和被代理类在编译期间就确定下来
*/
interface ClothesFactory{
void addClothes();
}
//代理对象
class ProxyFactory implements ClothesFactory{
private ClothesFactory clothesFactory;
public ProxyFactory(ClothesFactory clothesFactory){
this.clothesFactory=clothesFactory;
}
public void addClothes() {
System.out.println("这里是代理工厂");
clothesFactory.addClothes();
System.out.println("代理结束");
}
}
//被代理对象
class Factoyr implements ClothesFactory{
public void addClothes() {
System.out.println("这里是被代理对象");
}
}
public class ProxyTest {
public static void main(String[] args) {
Factoyr factoyr = new Factoyr();
new ProxyFactory(factoyr).addClothes();
}
}
在代理对象中构造方法,将代理对象放到构造函数的方法中,然后在代理对象中实现同一个方法。
动态代理
package com.zzh.test;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface Human {
void eat(String food);
String getMy();
}
class SuperMan implements Human{
public void eat(String food) {
System.out.println("我爱吃"+food);
}
public String getMy() {
return "I can fly";
}
}
//实现动态代理的问题 1.如何根据被代理类动态的创建一个代理类 2.当通过代理类的对象调用方法时,如何调用被代理对象的同名方法。
class JDKProxyFactory {
//调用此方法,返回一个代理类对象
public static Object getProxyInstance(Object obj){//obj:是被代理的对象
myInvocation myInvocation = new myInvocation();
myInvocation.bind(obj);
return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),myInvocation);
}
}
class myInvocation implements InvocationHandler{
private Object object;//需要被代理类赋值
public void bind(Object object) {
this.object = object;
}
//当通过代理类的对象 ,调用方法,就会自动调用如下的方法 invoke
//将被代理类要执行的方法的功能声明在invoke
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//代理类对象调用的方法
Object returnValue= method.invoke(object,args);
return returnValue;
}
}
public class JDKProxyTest {
public static void main(String[] args) {
//代理类的对象
Human proxy= (Human) JDKProxyFactory.getProxyInstance( new SuperMan());
proxy.eat("屎");
System.out.println(proxy.getMy());
}
}