在上一篇文章中我总结了下策略模式,这边文章我来回顾一下装饰模式。
装饰模式:动态的给对象增加一些额外的职责。
在这个概念中有两个重要的词 动态和额外。动态 具体变现在实际业务流程中可以根据业务需要对一个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
特此表示鸣谢