设计模式---代理模式
代理模式
概述
代码示例
public interface Subject {
public void sailBook();
}
public class RealSubject implements Subject {
public void sailBook() {
System.out.println("卖书");
}
}
public class ProxySubject implements Subject{
private RealSubject realSubject;
public void sailBook() {
dazhe();
if(realSubject == null) {
realSubject = new RealSubject();
}
realSubject.sailBook();
give();
}
public void dazhe() {
System.out.println("打折");
}
public void give() {
System.out.println("赠送代金券");
}
}
主函数
public class MainClass {
public static void main(String[] args) {
ProxySubject proxySubject = new ProxySubject();
proxySubject.sailBook();
}
}
动态代理
以上的部分我们需要手动代理,但是我们想要自动的让它进行代理
代码示例
public interface Subject {
public void sailBook();
}
public class RealSubject implements Subject {
public void sailBook() {
System.out.println("卖书");
}
}
public class MyHandler implements InvocationHandler {
private RealSubject realSubject;
public void setRealSubject(RealSubject realSubject) {
this.realSubject = realSubject;
}
public Object invoke(Object proxy, Method method, Object[] args){
Object result = null;
dazhe();
try {
result = method.invoke(realSubject, args);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
give();
return result;
}
public void dazhe() {
System.out.println("打折");
}
public void give() {
System.out.println("赠送代金券");
}
}
主函数
public class MainClass {
public static void main(String[] args) {
RealSubject realSubject = new RealSubject();
MyHandler myHandler = new MyHandler();
myHandler.setRealSubject(realSubject);
Subject proxySubject = (Subject)Proxy.newProxyInstance(RealSubject.class.getClassLoader(), realSubject.getClass().getInterfaces(), myHandler);
proxySubject.sailBook();
}
}