设计模式-装饰器模式(Decorator)
原创
©著作权归作者所有:来自51CTO博客作者每天在编程的原创作品,请联系作者获取转载授权,否则将追究法律责任
1.意图
动态地给一个对象添加一些额外的功能.
2.适用性
- 动态、透明的方式给单个对象添加职责。
- 如果不适合适用子类来进行扩展的时候,可以考虑适用装饰模式。
- 避免子类数目爆炸性增长。
3.结构

4.参与者
- Component: 定义一个对象接口,可以给这些对象动态地添加职责.
- ConcreteComponent: 定义一个对象,可以给这个对象添加职责.
- Decorator: 持有一个指向Component对象的引用,并定义一个与Component的接口一致的接口.
- ConcreteComponent: 向组件添加职责.
5.效果
1)优点:
- 比静态继承更灵活.
- 避免在层次结果高层的类有太多的特征.
2)缺点:
6.模式应用
- Java中的I/O流
- 面向切面编程AOP(思想相似)
7.实例
1)场景
一个软件公司由员工Employee组成,员工又分为开发人员Dev、领导Leader、经理Manager、QA部门领导QALeader。Dev职责是开发代码;QALeader职责不但能开发代码,而且能设计测试案例,写测试报告;Manager职责还能开发框架,发布版本。
2)UML图

3)代码
Employee类
public abstract class Employee {
public abstract void doSomething();
}
Dev类
public class Dev extends Employee {
@Override
public void doSomething() {
// TODO Auto-generated method stub
writeCode();
}
private void writeCode() {
// TODO Auto-generated method stub
System.out.println("I'm a programer,complete the code!");
System.out.println("---------------------------------------");
}
}
Leader类
public abstract class Leader extends Employee {
private Employee person;
public Leader(Employee person) {
super();
this.person = person;
}
@Override
public void doSomething() {
person.doSomething();
}
}
Manager类
public class Manager extends Leader {
public Manager(Employee person) {
super(person);
// TODO Auto-generated constructor stub
}
public void doSomething(){
begin();
super.doSomething();
end();
}
private void begin() {
// TODO Auto-generated method stub
System.out.println("Design the framework!");
System.out.println("---------------------------------------");
}
private void end() {
// TODO Auto-generated method stub
System.out.println("Release the verion!");
System.out.println("---------------------------------------");
}
}
QALeader类
public class QALeader extends Leader {
public QALeader(Employee person){
super(person);
}
@Override
public void doSomething() {
// TODO Auto-generated method stub
begin();
super.doSomething();
end();
}
private void end() {
// TODO Auto-generated method stub
System.out.println("Write the test reporter");
System.out.println("---------------------------------------");
}
private void begin() {
// TODO Auto-generated method stub
System.out.println("Write the test cases!");
System.out.println("---------------------------------------");
}
}
输出结果:
========leader1 doSomething==========
Write the test cases!
—————————————
I’m a programer,complete the code!
—————————————
Write the test reporter
—————————————
========leader2 doSomething==========
Design the framework!
—————————————
Write the test cases!
—————————————
I’m a programer,complete the code!
—————————————
Write the test reporter
—————————————
Release the verion!
—————————————