什么是代理模式,代理模式有哪几种
- 代理模式:为其他对象提供一种代理以控制对这个对象的访问。在某些情况下,一个对象不适合或者不能直接引用另一个对象,而代理对象可以在客户端和目标对象之间起到中介的作用。
- 分为静态代理和动态代理。
静态代理和动态代理有什么区别
- 静态代理需要我们自己创建代理对象(需要创建代理类),而动态代理的代理对象是自动生成的,我们不需要关心代理对象的生成过程。
代码实现
- 静态代理
public interface IShopPhone {
/**
* 购买手机
* @param phoneName 手机型号
*/
void shopPhone(String phoneName);
}
public class ZeroShopPhone implements IShopPhone {
@Override
public void shopPhone(String phoneName) {
System.out.println("Zero 成功购买: "+phoneName+" 手机");
}
}
public class ProxyShopPhone implements IShopPhone {
private ZeroShopPhone shopPhone;
public ProxyShopPhone(ZeroShopPhone shopPhone) {
super();
this.shopPhone = shopPhone;
}
@Override
public void shopPhone(String phoneName) {
System.out.println("我是代理商,我悄悄的拿走一个摄像头 →_→!");
this.shopPhone.shopPhone(phoneName);
}
}
public class Client {
public static void main(String[] args) {
IShopPhone zeroShopPhone = new ZeroShopPhone();
IShopPhone proxy = new ProxyShopPhone(zeroShopPhone);
proxy.shopPhone("IPhone X");
}
}
- 动态代理
我们可以将静态代理中的代理类去掉,在客户端中以反射的形式实现
public class Client {
public static void main(String[] args) {
IShopPhone zeroShopPhone = new ZeroShopPhone();
IShopPhone proxy = (IShopPhone) Proxy.newProxyInstance(
zeroShopPhone.getClass().getClassLoader(),
zeroShopPhone.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object obj, Method method, Object[] args) throws Throwable {
System.out.println("我是代理商,我悄悄的拿走一个摄像头 →_→!");
return method.invoke(zeroShopPhone, args);
}
});
proxy.shopPhone("IPhone X");
}
}
参考:https://www.jianshu.com/p/ebf55553bfe6
参考:https://www.jianshu.com/p/148940451575