设计模式--代理模式(proxy)
代理模式在日常生活中很常见,租房找中介代理找房,车辆上牌照找4S店代理上牌 等等很多例子。
代理模式的模式图
-
抽象角色:声明真实对象和代理对象的共同接口
-
代理角色:代理对象角色内部含有对真实对象的引用,从而可以操作真实对象,同时代理对象提供与真实对象相同的接口以便在任何时刻都能代替真实对象。同时,代理对象可以在执行真实对象操作时,附加其他的操作,相当于对真实对象进行封装。
-
真实对象:代理角色所代表的真实对象,是我们最终要引用的对象。
以一个具体场景举例: 内向男孩送美女礼物,有那心没那胆,只能找朋友代他去送。
public interface GiveGift {
//送鲜花
void giveFlowers();
}
美女实体:
@Data
public class BeautyGirl {
private String name;
}
真实对象:
public class NeiXiangBoy implements GiveGift {
private BeautyGirl beautyGirl;
public NeiXiangBoy(BeautyGirl beautyGirl) {
this.beautyGirl = beautyGirl;
}
@Override
public void giveFlowers() {
System.err.println("给" + beautyGirl.getName() + "送鲜花");
}
}
代理对象:(静态代理)
public class ProxyOfNeiXiangBoy implements GiveGift {
private NeiXiangBoy neiXiangBoy;
public ProxyOfNeiXiangBoy(BeautyGirl beautyGirl) {
this.neiXiangBoy = new NeiXiangBoy(beautyGirl);
}
//代理给美女送花
@Override
public void giveFlowers() {
//其实是内向男孩儿给美女送花
neiXiangBoy.giveFlowers();
}
}
静态代理模式测试类:
public class ProxyModeTest {
public static void main(String[] args) {
BeautyGirl beautyGirl = new BeautyGirl();
beautyGirl.setName("小方");
DaiLiOfNeiXiangBoy daiLiOfNeiXiangBoy = new DaiLiOfNeiXiangBoy(beautyGirl);
daiLiOfNeiXiangBoy.giveFlowers();
}
}
动态代理角色处理器
public class ProxyHandler implements InvocationHandler {
private NeiXiangBoy neiXiangBoy;
public ProxyHandler(NeiXiangBoy neiXiangBoy) {
this.neiXiangBoy = neiXiangBoy;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.err.println("方法开始前做一些事情");
//激活调用的方法
Object object = method.invoke(neiXiangBoy, args);
//方法结束后做一些事情
System.err.println("方法结束后做一些事情");
return object;
}
}
动态代理模式测试类
public class DynamicProxyModeTest {
public static void main(String[] args) {
BeautyGirl beautyGirl = new BeautyGirl();
beautyGirl.setName("小方");
NeiXiangBoy neiXiangBoy = new NeiXiangBoy(beautyGirl);
ProxyHandler proxyHandler = new ProxyHandler(neiXiangBoy);
GiveGift giveGift = (GiveGift) Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[]{GiveGift.class}, proxyHandler);
giveGift.giveFlowers();
}
}