---
title: "五、装饰模式"
author: "bolan392"
date: "2011-11-10T14:29:14Z"
tags: []
categories: ["企业架构"]
slug: "untitled"
draft: false
lastmod: "2011-11-10T14:35:35Z"
id: 1250249
url: "https://bolan392.iteye.com/blog/1250249"
---

1.什么是装饰模式

   装饰模式（Decorator），动态的给一个对象添加一些额外的职责，就增加功能来说，装饰模式比生成子类更加灵活。装饰模式是为已有功能添加更多功能的一种方式。

  

2.为什么使用装饰模式

   当系统需要新功能的时候，是向旧的类中添加新的代码。这些新的代码通常装饰了原有类的核心职责或主要行为，这种做法增加了主类的复杂度。而装饰模式可以很好的解决这个问题，它把每个需要装饰的功能放在单独的类中，并让这个类包装它所要装饰的对象，因此，当需要执行特殊行为时，客户代码就可以根据需要有选择地、按顺序地使用装饰功能包装对象了。装饰模式最大的优点就是把类中的装饰功能从类中搬移出去，这样可以简化原有的类，并且把类的核心职责和装饰功能分开。

3.怎样使用装饰模式 

![](http://i.6.cn/cvbnm/96/e8/0f/ec63bacd5dbc41440906cfbc36761318.png)

Component接口

```
public interface Component {

	public void operation();

}
```

   
ConcreteComponent类

```
public class ConcreteComponent implements Component {

	public void operation(){
		//具体对象的操作
		//。。。。。。
	}

}
```

 

 

Decorator类

```
public class Decorator implements Component {

	public Component m_Component;
	
	public void setComponent(Component m_Component){
		this.m_Component = m_Component;
	}

	public void operation(){
		if(null != m_Component){
			m_Component.operation();
		}	
	}
}
```

 

DecoratorA类

```
public class DecoratorA implements Decorator {

	private String addedState;	

	public void operation(){
		super.operation();//首先执行父类的操作
		//再执行本类的功能......相当于对原来的功能进行了装饰
		System.out.println(addedState);
	}
}
```

 

DecoratorB类

```
public class DecoratorB implements Decorator {
	//本类独有的方法
	public void addBehavior(){
		
	}

	public void operation(){
		super.operation();//首先执行父类的操作
		addBehavior();//调用本类独有方法，相当于装饰
	}

}
```