---
title: "第八章 装饰模式"
author: "crawler"
date: "2013-05-17T08:55:31Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2013-05-17T09:21:00Z"
id: 1870671
url: "https://crawler.iteye.com/blog/1870671"
---

**1.装饰模式**

动态地给对象添加一些额外的职责。就功能来说装饰模式相比生成子类更为灵活。

动态地扩展一个对象的功能，而不需要改变原始类代码的一种成熟模式。

在装饰模式中，“具体组件”类和“具体装饰”类是该模式中的最重要的两个角色。  
**2装饰模式-结构**

装饰模式的结构中包括四种角色：

- 抽象组件（Component）
- 具体组件（ConcreteComponent）
- 装饰（Decorator）
- 具体装饰（ConcreteDecotator）

![](http://dl.iteye.com/upload/attachment/0084/6052/e8a36853-6553-39b9-bb02-bba2dd5408db.jpg)  
 装饰模式的核心就是在于装饰的构造方法关联了抽象组件的引用，而具体组件和具体装饰都是属于抽象组件的子类，所以在构造具体装饰的时候，可以把不同的具体装饰作为引用来构造自己，即实现责任的扩充。

**3装饰模式-场景描述**

麻雀可以在飞100米的基础上连续飞50米

**4装饰模式-场景分析**

 

- 抽象组件  
  鸟 Bird
- 具体组件  
  麻雀 Sparrow
- 装饰  
  装饰 Decorator
- 具体装饰  
  具体装饰 SparrowDecorator

![](http://dl.iteye.com/upload/attachment/0084/6054/e2fca1a5-ccef-3b4f-b503-0120a690d958.png)  
 **5装饰模式-代码实现**

```
package patterns.decorator;
/**
 * 抽象组件
 * @author Administrator
 *
 */
public abstract class Bird {
	public abstract double fly();
}

package patterns.decorator;
/**
 * 具体组件
 * @author Administrator
 *
 */
public class Sparrow extends Bird {

	@Override
	public double fly() {
		return 100;
	}

}


package patterns.decorator;
/**
 * 装饰角色
 * @author Administrator
 *
 */
public abstract class Decorator extends Bird {
	public Bird bird;

	public Decorator(Bird bird) {
		this.bird = bird;
	}
}


package patterns.decorator;
/**
 * 具体装饰角色
 * @author Administrator
 *
 */
public class SparrowDecorator extends Decorator {
	public double DISTANCE = 50;
	public SparrowDecorator(Bird bird) {
		super(bird);
	}

	@Override
	public double fly() {
		return bird.fly()+DISTANCE;
	}

}


package patterns.decorator;

public class Client {
	public static void main(String[] args) {
		Bird bird = new Sparrow();
		System.out.println(bird.fly());
		
		Decorator decorator = new SparrowDecorator(bird);
		System.out.println(decorator.fly());
		
		Decorator decorator2 = new SparrowDecorator(decorator);
		System.out.println(decorator2.fly());
	}
}
```