首页
学习
活动
专区
圈层
工具
发布

常用开源框架中设计模式使用分析- 装饰器模式(Decorator Pattern)

九、装饰器模式(Decorator Pattern)

9.1 介绍

装饰器模式是一种结构性模式,它作用是对对象已有功能进行增强,但是不改变原有对象结构。这避免了通过继承方式进行功能扩充导致的类体系臃肿。

装饰器模式是一种结构性模式,它作用是对对象已有功能进行增强,但是不改变原有对象结构。这避免了通过继承方式进行功能扩充导致的类体系臃肿。

9.2 Spring中BeanDefinitionDecorator

先看下类图:

image.png

如图ScopedProxyBeanDefinitionDecorator实现了decorate方法用来对scope作用域为request的bean定义进行包装。 具体时序图为:

image.png

代码语言:javascript
复制
class ScopedProxyBeanDefinitionDecorator implements BeanDefinitionDecorator {

    private static final String PROXY_TARGET_CLASS = "proxy-target-class";


    @Override
    public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definition, ParserContext parserContext) {
        boolean proxyTargetClass = true;
        if (node instanceof Element) {
            Element ele = (Element) node;
            if (ele.hasAttribute(PROXY_TARGET_CLASS)) {
                proxyTargetClass = Boolean.valueOf(ele.getAttribute(PROXY_TARGET_CLASS));
            }
        }

        // 创建scoped的代理类,并注册到容器
        BeanDefinitionHolder holder =
                ScopedProxyUtils.createScopedProxy(definition, parserContext.getRegistry(), proxyTargetClass);
        String targetBeanName = ScopedProxyUtils.getTargetBeanName(definition.getBeanName());
        parserContext.getReaderContext().fireComponentRegistered(
                new BeanComponentDefinition(definition.getBeanDefinition(), targetBeanName));
        return holder;
    }

}

关于ScopedProxyBeanDefinitionDecorator干啥用的那:

代码语言:javascript
复制
  <bean id="lavaPvgInfo" class="com.alibaba.lava.privilege.PrivilegeInfo"
        scope="request">
        <property name="aesKey" value="666" />
        <aop:scoped-proxy />
    </bean>

其实就是处理<aop:scoped-proxy /> 的,具体作用是包装lavaPvgInfo的bean定义为ScopedProxyFactoryBean,作用是实现request作用域bean.

9.3 commons-collections包中ListUtils

image.png

如图

ListUtils中的四个方法分别依赖list的四种装饰器类对List功能进行扩充和限制。 其中FixedSizeList类通过禁止add/remove操作保证list的大小固定,但是可以修改元素内容 其中UnmodifiableList类通过禁用add,clear,remove,set,保证list的内容不被修改 其中SynchronizedList类通过使用Lock 来保证add,set,get,remove等的同步安全 其中LazyList类则当调用get方法发现list里面不存在对象时候,自动使用factory创建对象.

9.4 使用场景

  • 在不改变原有类结构基础上,新增或者限制或者改造功能时候。
下一篇
举报
领券