装饰模式和动态代理模式是都可以用来给已存在的类的方法增加前、后置的代码。
代理模式
代理类与被代理类都要实现的接口:
public interface Subject {
public void print();
}
被代理类:
public class RealSubject implements Subject{
@Override
public void print() {
System.out.println("real subject");
}
}
代理类:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SubjectProxy implements InvocationHandler {
private Object o;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss.SSSSSSS");
public SubjectProxy(Object subject) {
this.o=subject;
}
@Override
public Object invoke(Object proxy, Method m, Object[] args)
throws Throwable {
beforeMethod();
m.invoke(o, args);
afterMethod();
return null;
}
private void afterMethod() throws InterruptedException {
Thread.sleep(666);
System.out.println(format.format(new Date()));
}
private void beforeMethod() {
System.out.println(format.format(new Date()));
}
}
Test:
import java.lang.reflect.Proxy;
public class Test {
public static void main(String[] args) {
Subject subject = new RealSubject();
Subject proxy = (Subject)Proxy.newProxyInstance(
subject.getClass().getClassLoader(),
subject.getClass().getInterfaces(),
new SubjectProxy(subject));
proxy.print();
}
}
输出结果:
2012-10-30-16:21:13.0000389
real subject
2012-10-30-16:21:14.0000056
real subject
2012-10-30-16:21:14.0000056
装饰模式
interface Subject {
void action();
}
class SubjectImpl implements Subject{
public void action() {
System.out.println("action");
}
}
abstract class Decorator implements Subject {
protected Subject subject;
public void setSubject(Subject subject) {
this.subject = subject;
}
public void action() {
subject.action();
}
}
class DecoratorAfter extends Decorator {
public void action() {
super.action();
afterAction();
System.out.println("DecoratorAfter");
}
public void afterAction() {
System.out.println("after");
}
}
class DecoratorBefore extends Decorator {
public void action() {
beforeAction();
super.action();
System.out.println("DecoratorBefore");
}
public void beforeAction() {
System.out.println("before");
}
}
public class Test {
public static void main(String[] args) {
SubjectImpl subject = new SubjectImpl();
DecoratorAfter d1 = new DecoratorAfter();
DecoratorBefore d2 = new DecoratorBefore();
d1.setSubject(subject);
d2.setSubject(d1);
d2.action();
}
}
输出结果:
before
action
after
DecoratorAfter
DecoratorBefore