代理模式
代理模式:为其他对象提供一种代理以控制对这个对象的访问。
1,静态代理
硬编码编写代理类,容易产生大量代理类(摘自网上)
//代理接口 public interface GiveGift { void giveDolls(); void giveFlowers(); void giveChocolate(); } //追求者类 public class Pursuit implements GiveGift { SchoolGirl mm; public Pursuit(SchoolGirl mm) { this.mm = mm; } public void giveDolls() { System.out.println(mm.name + " 送你洋娃娃"); } public void giveFlowers() { System.out.println(mm.name + " 送你鲜花"); } public void giveChocolate() { System.out.println(mm.name + " 送你巧克力"); } } //代理类 public class Proxy implements GiveGift { Pursuit gg; public Proxy(SchoolGirl mm) { gg = new Pursuit(mm); } public void giveChocolate() { gg.giveChocolate(); } public void giveDolls() { gg.giveDolls(); } public void giveFlowers() { gg.giveFlowers(); } } //客户端代码 public class Main { public static void main(String[] args) { SchoolGirl jiaojiao = new SchoolGirl(); jiaojiao.setName("李娇娇"); Proxy daili = new Proxy(jiaojiao); daili.giveDolls(); daili.giveFlowers(); daili.giveChocolate(); } }
2,动态代理
java中有接口InvocationHandler(java.lang.reflect)
通过实现一个InvocationHandler,产生一个动态代理类。
编写一个接口如下:
public interface Subject { public void doSomething(); }
实现接口:
public class RealSubject implements Subject{ @Override public void doSomething() { // TODO Auto-generated method stub System.out.println("call doSomething"); }
编写动态代理类:
1 import java.lang.reflect.InvocationHandler; 2 import java.lang.reflect.Method; 3 4 public class ProxyHandler implements InvocationHandler { 5 6 private Object proxied; 7 8 public ProxyHandler(Object proxied) { 9 this.proxied=proxied; 10 } 11 12 @Override 13 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 14 // TODO Auto-generated method stub 15 16 System.out.println("开始执行"); 17 Object obj= method.invoke(proxied, args); 18 System.out.println("结束执行"); 19 return obj; 20 } 21 22 }
client调用:
import java.lang.reflect.Proxy; public class DynamicProxy { public static void main(String[] args) { RealSubject real=new RealSubject(); Subject proxySubject=(Subject)Proxy.newProxyInstance(Subject.class.getClassLoader(), new Class[]{Subject.class}, new ProxyHandler(new RealSubject())); proxySubject.doSomething(); System.out.println(Proxy.isProxyClass(proxySubject.getClass())); } }