装饰模式和代理模式
为什么把这两种模式放在一起,因为个人觉得这两种模式太相似了;先看他们各自的定义:
装饰模式:在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。
在装饰模式中的各个角色有:
(1)抽象构件(Component)角色:给出一个抽象接口,以规范准备接收附加责任的对象。
(2)具体构件(Concrete Component)角色:定义一个将要接收附加责任的类。
(3)装饰对象(Decorator)角色:持有一个构件(Component)对象的实例,并实现一个与抽象构件接口一致的接口。
关系如下图:

代码如下:
抽象构件
public interface Component { public void doAction(); }
具体构件
public class ConcreteComponent implements Component{ public void doAction() { System.out.println("被装饰类ConcreteComponent doAction()"); } }
装饰类:
public class Decorator implements Component{ private Component component; public Decorator(Component component) { this.component=component; } public void doAction() { run(); component.doAction(); } public void run() { System.out.println("新增缓冲功能"); } }
测试如下:
public class Test { public static void main(String[] args) { Component c=new Decorator(new ConcreteComponent()); c.doAction(); } }
输出:
新增缓冲功能
被装饰类ConcreteComponent doAction()
代理模式:为其他对象提供一种代理以控制对这个对象的访问。在某些情况下,一个对象不适合或者不能直接引用另一个对象,而代理对象可以在客户端和目标对象之间起到中介的作用。
(1) 抽象角色:通过接口或抽象类声明真实角色实现的业务方法。
(2) 代理角色:实现抽象角色,是真实角色的代理,通过真实角色的业务逻辑方法来实现抽象方法,并可以附加自己的操作。
(4) 真实角色:实现抽象角色,定义真实角色所要实现的业务逻辑,供代理角色调用。
关系如下图:

代码如下(为了更好区分他们,还是以上面例子为例,其实只要把Decorator 类稍作修改即可):
抽象角色:
public interface Component { public void doAction(); }
代理角色:
public class ConcreteComponent implements Component{ public void doAction() { System.out.println("被代理ConcreteComponent doAction()"); } }
真实角色:
public class Decorator implements Component{ private Component component; public Decorator() { component=new ConcreteComponent(); } public void doAction() { run(); component.doAction(); } public void run() { System.out.println("新增代理功能功能"); } }
测试如下:
public class Test { public static void main(String[] args) { Component c=new Decorator(); c.doAction(); } }
输出:
新增代理功能功能
被代理ConcreteComponent doAction()
从两种模式的代码可以看出:装饰模式是把要装饰的对象(ConcreteComponent)当作参数传入,而且被装饰的对象是动态的;这也是和代理模式的区别,代理模式本身持有这个对象,不需要从外部传入;
功能上代理模式注重的是隔离限制,让外部不能访问你实际的调用对象,比如权限控制,装饰模式注重的是功能的拓展,在同一个方法下实现更多的功能。
浙公网安备 33010602011771号