1.代理模式就是给一个对象提供一个代理对象,由这个代理对象控制对原对象的引用,便代理类在客户端和原对象之间起到一个中介的作用.
2.代理对象主要由3部分组成:抽象目标类、具全的目标类和代理类.
3.代理模式可分为静态代理与动态代理
静态代理例子:
package com.proxy;
public interface Test {
public void doLogic(String name);
}
package com.proxy;
public class TestImpl implements Test{
public void doLogic(String name) {
System.out.println(name + "开始处理业务逻辑!");
}
}
package com.proxy;
public class TestProxy implements Test{
private Test test;
public TestProxy(Test test){
this.test = test;
}
public void doLogic(String name) {
System.out.println("开始日志............");
test.doLogic(name);
System.out.println("结束日志............");
}
}
package com.proxy;
public class Client {
public static void main(String[] args) {
TestProxy proxy = new TestProxy(new TestImpl());
proxy.doLogic("小明");
}
}
动态代理例子:
package com.proxy2;
public interface Test {
public void doLogic(String name);
}
package com.proxy2;
public class TestImpl implements Test{
public void doLogic(String name) {
System.out.println(name + "处理业务中..........");
}
}
package com.proxy2;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class LogProxy implements InvocationHandler{
private Object delegate;
//绑定代理对象
public Object bind(Object delegate){
this.delegate = delegate;
return Proxy.newProxyInstance(delegate.getClass().getClassLoader(), delegate.getClass().getInterfaces(), this);
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result = null;
try {
System.out.println("【日志】业务处理开始.......");
result = method.invoke(delegate, args);
System.out.println("【日志】业务处理结束.........");
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
package com.proxy2;
public class Client {
public static void main(String[] args) {
Test test = new TestImpl();
LogProxy proxy = new LogProxy();
Test s = (Test)proxy.bind(test);
s.doLogic("小白");
}
}
说明:一般被代理的目标类要写接口,
(return Proxy.newProxyInstance(delegate.getClass().getClassLoader(), delegate.getClass().getInterfaces(), this);
)
当然你也可以用开源框架CGlib来实现.
4.UML