1、装饰模式
装饰模式:动态的给对象添加一些额外的职责,例如,给相片加各种不同的相框(相框就是装饰器)。
2、装饰模式的结构
-
角色
-
抽象组件(Component): 抽象组件定义了需要进行装饰的方法,也就是“被装饰者”角色;
-
具体组件(ConcreteComponent): 具体组件是抽象主件的一个子类;
-
装饰(Decorator):
-
具体装饰(ConcreteDecorator):具体装饰是”装饰“角色的一个非抽象子类。
-
-
类图

3、装饰模式举例
问题:给麻雀安装智能电子翅膀
抽象组件: Bird.java
1 package com.nick.pattern.decorator;
2 /**
3 * 抽象组件(被装饰者)
4 * 定义一个接口,接口中包括需要被装饰的一个抽象方法
5 * @author nick
6 */
7 public interface Bird {
8 public abstract int fly();
9 }
具体组件:Sparrow.java
1 package com.nick.pattern.decorator;
2 /**
3 * 具体组件(实现抽象组件)
4 * @author nick
5 */
6 public class Sparrow implements Bird {
7 public final int DINSTANCE = 100;
8 @Override
9 public int fly() {
10 return DINSTANCE;
11 }
12 }
装饰器: Decorator.java
1 package com.nick.pattern.decorator;
2 /**
3 * 装饰(装饰具体组件,包含被装饰者的引用)
4 * @author nick
5 */
6 public abstract class Decorator implements Bird {
7 Bird bird; //引用抽象组件
8 public Decorator(Bird bird) {
9 this.bird = bird;
10 }
11 public abstract int eleFly(); //装饰器中的装饰方法
12 }
具体装饰1:
1 package com.nick.pattern.decorator;
2 /**
3 * 具体装饰(装饰者的子类--电子翅膀)
4 * @author nick
5 */
6 public class SparrowDecorator extends Decorator {
7 public final int DISTANCE = 50; //eleFly()方法(模拟电子翅膀)能飞50米
8 public SparrowDecorator(Bird bird) {
9 super(bird);
10 }
11 @Override
12 public int fly() {
13 int distance = 0;
14 distance = bird.fly() + eleFly();
15 return distance;
16 }
17 @Override
18 public int eleFly() {
19 return DISTANCE;
20 }
21 }
具体装饰2:
1 package com.nick.pattern.decorator;
2 /**
3 * 具体装饰2(喷气装置)
4 * @author
5 */
6 public class SparrowDecorator2 extends Decorator{
7 public final int DISTANCE = 100; //eleFly()方法(模拟喷气装置)能飞20米
8 public SparrowDecorator2(Bird bird) {
9 super(bird);
10 }
11 @Override
12 public int fly() {
13 int distance=0;
14 distance = bird.fly()+eleFly();
15 return distance;
16 }
17 @Override
18 public int eleFly() {
19 return DISTANCE;
20 }
21 }
主程序:
package com.nick.pattern.decorator;
/**
* 主程序
*/
public class Application {
public static void main(String[] args) {
Bird bird = new Sparrow();
System.out.println("没安装电子翅膀的麻雀能飞行的距离:"+bird.fly());
bird = new SparrowDecorator(bird);
System.out.println("安装1个电子翅膀的麻雀能飞行的距离:"+bird.fly());
bird = new SparrowDecorator(bird);
System.out.println("安装2个电子翅膀的麻雀能飞行的距离:"+bird.fly());
bird = new SparrowDecorator2(bird);
System.out.println("安装1个喷气装置后能飞行的距离:" +bird.fly());
}
}
运行结果:

4、装饰器模式的优缺点
-
优点1:被装饰者和装饰者是弱耦合关系,由于装饰依赖于抽象组件,因此具体装饰只知道它要它要装饰的对象是抽象组件的某一个子类的实例,但不需要知道具体是哪一个具体的实例。
-
优点2:装饰模式满足“开-闭原则”。不必修改具体组件,就可以增加新的针对该组件的具体装饰。
-
优点3:可以使用多个具体装饰来装饰具体组件的实例。