动态代理与装饰模式

装饰模式和动态代理模式是都可以用来给已存在的类的方法增加前、后置的代码。

代理模式

代理类与被代理类都要实现的接口:

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

装饰模式

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值