赞
踩
- // common interface
- public interface IRunner {
- public void run();
- }
-
- //target class
- public class Runner implements IRunner {
- @Override
- public void run() {
- System.out.println("运动员在跑步...");
- }
- }
-
- //decoration class
- public class RunnerWithJet implements IRunner {
- private IRunner runner;
-
- public RunnerWithJet(IRunner runner) {
- this.runner = runner;
- }
-
- @Override
- public void run() {
- System.out.println("给运动员屁股后加一个推进装置...");
- runner.run();
- }
- }
- public interface Person {
- void work();
- }
-
- public class Student implements Person {
- @Override
- public void work() {
- System.out.println("sudent is studying");
- }
- }
-
- public class ProxyStudent {
- private Student tar;
-
- public ProxyStudent(Student tar) {
- this.tar = tar;
- }
-
- public Object getProxyInstance(){
- return Proxy.newProxyInstance(tar.getClass().getClassLoader(), tar.getClass().getInterfaces(),
- new InvocationHandler() {
- @Override
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- if ("work".equals(method.getName())){
- System.out.println("student is studying hard");
- return null;
- }else{
- return method.invoke(tar,args);
- }
- }
- });
- }
-
- }
-
- public class TestDemo {
- @Test
- public void test01(){
- Student stu = new Student();
- stu.work();
- Person proxyStu = (Person) new ProxyStudent(stu).getProxyInstance();
- proxyStu.work();
- }
- }
1、代理模式和装饰模式作用都是对特定类的功能进行增强;
2、装饰模式:目标对象和装饰对象要实现相同的接口;如果接口中的方法较多,代码会比较冗余;
3、动态代理:不用和目标对象实现相同的接口,而且能够控制方法是否执行,或在方法执行前后做一些额外的操作;目标对象至少 要实现一个接口,否则无法使用动态代理;
4、实例:spring 中的aop 本质就是使用的代理技术;而java.io包中的包装流就是用的装饰模式;
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。