设计模式-装饰模式

在上一篇文章中我总结了下策略模式,这边文章我来回顾一下装饰模式。
装饰模式:动态的给对象增加一些额外的职责。
这里写图片描述

在这个概念中有两个重要的词 动态和额外。动态 具体变现在实际业务流程中可以根据业务需要对一个ConcreteComponent 对象进行任意次数的增加装饰。额外 代表的是与业务主体所要处理的核心业务无关的装饰部分,例如:模特走台核心的行为是走秀,在走秀之前我们要为模特进行化妆和选衣搭配等装饰行为。这个模式的核心在于将为促成某一目的的行为分出装饰部分和核心部分,从而避免在核心职责中引入过多的装饰部分使得核心职责过于冗杂。

package decorator;

/**
 * @author Created by yanjy on 2017/11/14.
 */
public interface Model {
    void show();
}

package decorator.impl;

import decorator.Model;

/**
 * @author Created by yanjy on 2017/11/14.
 */
public class FashionModelImpl implements Model {
    @Override
    public void show() {
        System.out.println("hi guys Look at me, i`m the fashion!");
    }
}

package decorator.impl;

import decorator.AbstractDecorator;

/**
 * @author Created by yanjy on 2017/11/14.
 */
public class WearClothesDecoratorImpl extends AbstractDecorator {
    @Override
    public void show() {
        System.out.println("please wear the clothes firstly");
        model.show();
    }
}

package decorator.impl;

import decorator.AbstractDecorator;

/**
 * @author Created by yanjy on 2017/11/14.
 */
public class WearShoesDecoratorImpl extends AbstractDecorator {

    @Override
    public void show() {
        System.out.println("please wear the shoes secondly");
        model.show();
    }
}

package decorator;

import decorator.impl.FashionModelImpl;
import decorator.impl.WearClothesDecoratorImpl;
import decorator.impl.WearShoesDecoratorImpl;

/**
 * @author Created by yanjy on 2017/11/14.
 */
public class Stage {

    public static void main(String[] args) {
        Model model = new FashionModelImpl();

        AbstractDecorator clothesDecorator = new WearClothesDecoratorImpl();
        AbstractDecorator shoesDecorator = new WearShoesDecoratorImpl();

        clothesDecorator.decorator(model);
        shoesDecorator.decorator(clothesDecorator);

        shoesDecorator.show();
    }

}

在使用装饰模式的时候一定要时刻注意装饰的顺序,以免造成逻辑上的混乱。例如:我们在做数据分析的时候,一般分为数据采集,数据清洗,数据归类,数据分析。前三个可以称之为装饰,切顺序极为重要。如果在数据采集后直接归类会导致很多脏数据的流入分类的数据中,对数据清洗造成极大的困难。

本文参考了
《大话设计模式》
http://design-patterns.readthedocs.io/zh_CN/latest/structural_patterns/decorator.html
特此表示鸣谢

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值