静态代理
利用程序实现客户通过中介向房东租房的案例:
优缺点理解:
代理模式的具体步骤:
动态代理
同样是以租房为例:
需要代理的类是租房的Rent类:
Rent.java
package org.example.Test;
public interface Rent {
public void rent();
}
Host.java
package org.example.Test;
public class Host implements Rent{
@Override
public void rent() {
System.out.println("房东要出租房子");
}
}
ProxyInvocation.java
package org.example.Test;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyInvocation implements InvocationHandler {
//被代理的接口
private Rent rent;//租房动作需要被代理
//生成得到代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),rent.getClass().getInterfaces(),this);
}
//处理代理实例,并返回结果
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//动态代理的本质,利用反射机制实现
Object result=method.invoke(rent,args);
return result;
}
public void setRent(Rent rent){
this.rent=rent;
}
}
Client.java
package org.example.Test;
public class Client {
public static void main(String[] args) {
//真实角色
Host host=new Host();
//代理角色
ProxyInvocation proxy=new ProxyInvocation();
//通过调用程序处理角色来处理我们要调用的接口对象
proxy.setRent(host);
Rent p=(Rent)proxy.getProxy();
p.rent();
}
}
自己利用userService以及userServiceImpl实现动态代理:
userService.java
package org.example.Test;
public interface userService {
public void oneSelf();
}
userServiceImpl.java
package org.example.Test;
public class userServiceImpl implements userService{
@Override
public void oneSelf() {
System.out.println("测试动态代理");
}
}
ProxyInvocation.java
package org.example.Test;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyInvocation implements InvocationHandler {
private Object us;
public void setUs(Object us){
this.us=us;
}
private Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(), us.getClass().getInterfaces(),this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object b=method.invoke(us,args);
return b;
}
}
Test.java
package org.example.Test;
public class Test {
public static void main(String[] args) {
//真实角色
userServiceImpl us=new userServiceImpl();
//代理角色
ProxyInvocation proxy=new ProxyInvocation();
proxy.setUs(us);
us.oneSelf();
}
}
标签:java,--,Object,代理,us,静态,Test,public
From: https://www.cnblogs.com/liuzijin/p/17396766.html