一、装饰模式
1、示例代码
// 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();
}
}
2、概念
- 装饰模式指的是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象 ;
二、代理模式
1、示例代码
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();
}
}
2、概念
- 用来修改已经具有的对象的方法,控制方法是否执行,或在方法执行之前和执行之后做一些额外的操作;
三、对比总结
1、代理模式和装饰模式作用都是对特定类的功能进行增强;
2、装饰模式:目标对象和装饰对象要实现相同的接口;如果接口中的方法较多,代码会比较冗余;
3、动态代理:不用和目标对象实现相同的接口,而且能够控制方法是否执行,或在方法执行前后做一些额外的操作;目标对象至少 要实现一个接口,否则无法使用动态代理;
4、实例:spring 中的aop 本质就是使用的代理技术;而java.io包中的包装流就是用的装饰模式;