首页 > 代码库 > java设计模式--代理模式

java设计模式--代理模式

代理模式 proxy:为其他对象提供一种代理,并以控制对这个对象的访问,好比经纪人和明星之间的关系,经纪人就是明星的代理类。简单的就是在方法调用前后做处理,AOP思想,好处就是不改变原来类方法的基础上,动态的添加其他方法。

 

代理模式的3个角色

1.抽象角色2.真实角色

3.代理角色

 

1.静态代理

代理类调用被代理类的方法。

2.动态代理---比较常用

public interface People {            void eat();    }
public class Zhangsan implements People {    public void eat(){        System.out.println("吃饭");    }}

代理类---需实现InvocationHandler 接口

public class PorxyHandler implements InvocationHandler {        People people = null;        public PorxyHandler(People people) {        this.people = people;    }    public Object invoke(Object proxy, Method method, Object[] args)            throws Throwable {        this.before();        method.invoke(people, args);        this.after();        return null;    }        private void before(){        System.out.println("洗手");    }        private void after(){        System.out.println("洗碗");    }}
public class Client {        public static void main(String[] args) {        People people = (People)Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[]{People.class}, new ProxyHandler(new Zhangsan()));        people.eat();            }}

 

java设计模式--代理模式