装饰模式能够实现动态的为对象添加功能,是从一个对象外部来给对象添加功能。通常给对象添加功能,要么直接修改对象添加相应的功能,要么派生对应的子类来扩展,抑或是使用对象组合的方式。显然,直接修改对应的类这种方式并不可取。在面向对象的设计中,而我们也应该尽量使用对象组合,而不是对象继承来扩展和复用功能。装饰器模式就是基于对象组合的方式,可以很灵活的给对象添加所需要的功能。装饰器模式的本质就是动态组合。动态是手段,组合才是目的。总之,装饰模式是通过把复杂的功能简单化,分散化,然后再运行期间,根据需要来动态组合的这样一个模式。

装饰器模式

假设我们有一个水果篮子,厘米可以装苹果,香蕉、或者橘子。这是可以典型的应用装饰器模式,比如我们用三个修饰器来修饰水果篮子里面装的内容。假设我们使用继承的话,那么要想获得所有情况,根据排列组合那么就有8种可能,需要有7个子类(空篮子就是本身,不需继承了)。装饰器模式就简单多了。

Basket.java

1
2
3
4
5
6
7
8
package com.yutian.design.decorator;
/**
* Created by wuzhenxing on 16/3/7.
*/
public interface Basket {
public void show();
}

Original.java

1
2
3
4
5
6
7
8
9
10
package com.yutian.design.decorator;
/**
* Created by wuzhenxing on 16/3/7.
*/
public class Original implements Basket {
public void show() {
System.out.println("The basket contains");
}
}

AppleDecorator.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.yutian.design.decorator;
/**
* Created by wuzhenxing on 16/3/7.
*/
public class AppleDecorator implements Basket {
private Basket basket;
public AppleDecorator(Basket basket){
super();
this.basket = basket;
}
public void show(){
basket.show();
System.out.println("An Apple");
}
}

BananaDecorator.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.yutian.design.decorator;
/**
* Created by wuzhenxing on 16/3/7.
*/
public class BananaDecorator implements Basket {
private Basket basket;
public BananaDecorator(Basket basket){
super();
this.basket = basket;
}
public void show(){
basket.show();
System.out.println("A Banana");
}
}

OrangeDecorator.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.yutian.design.decorator;
/**
* Created by wuzhenxing on 16/3/7.
*/
public class OrangeDecorator implements Basket {
private Basket basket;
public OrangeDecorator(Basket basket){
super();
this.basket = basket;
}
public void show(){
basket.show();
System.out.println("An Oranage");
}
}

测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.yutian.design.decorator;
/**
* Created by wuzhenxing on 16/3/7.
*/
public class Decorator {
public static void main(String[] args) {
Basket basket = new Original();
Basket myBasket = new AppleDecorator(new BananaDecorator(new OrangeDecorator(basket)));
myBasket.show();
}
}