代理模式分为静态代理和动态代理。我们拿链家来举例子,我们本人是真实的对象,有真实的业务需求:需要去找房子;链家是中介,是代理类,他来帮我执行找房子的这个操作。
静态代理:
1.实现一个接口
public interface SearchHome { public void search();}
2.构建实现接口的委托类
public class Master implements SearchHome { @Override public void search() { System.out.println("寻找房子"); }}
3.构建代理类
public class HomeLink implements SearchHome{ private SearchHome sh; public HomeLink(SearchHome sh) { super(); this.sh = sh; } @Override public void search() { System.out.println("链家帮您找房子..."); sh.search(); System.out.println("链家帮您找到了..."); }}
4.客户端:
public class Main { public static void main(String[] args) { SearchHome sh = new HomeLink(new Master()); sh.search(); }}
动态代理:
静态代理是代理类和委托类在java代码中绑定在一起,不方便管理。相比静态代理, 动态代理可以很方便的对委托类的方法进行统一处理。动态代理是在java代码运行时生成,动态代理又分为jdk动态代理和cglib动态代理。
1.定义接口:
public interface SearchHome { void search(); }
2.定义委托类:
public class Master implements SearchHome { @Override public void search() { System.out.println("寻找房子"); }}
3.定义动态代理类
public class MyProxy implements InvocationHandler { private Object target; public MyProxy(Object target) { super(); this.target = target; } public Object newInstance() { return Proxy.newProxyInstance(this.getClass().getClassLoader(), this.target.getClass().getInterfaces(),this); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result = null; System.out.println("链家开始找..."); result = method.invoke(this.target, args); System.out.println("链家开始找..."); return result; }}
4.main
public class Main { public static void main(String[] args) { SearchHome sh = (SearchHome) new MyProxy(new Master()).newInstance(); sh.search(); }}