首页 > 代码库 > 代理模式
代理模式
代理模式:为其他对象提供一种代理以控制对这个对象的访问。
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())); } }
代理模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。