通俗的说明一下装饰者模式。举一个平常生活中的例子衣服,我们都知道衣服有不同的颜色,假设衣服初始颜色是纯洁的白色,现在我们要对这衣服装饰的更加漂亮,这时我们需要加入其他的颜色进行装饰,这些颜色可以是红色、蓝色、绿色等等。根据装饰者模式的原理我们可以从以上的例子中抽象出各种角色出来。
首先被装饰者:衣服
被装饰者实体:白色的衣服
装饰者:颜色(红、蓝、绿等等)
装饰者实体:在白衣服的基础上天了其他颜色的衣服。
具体代码实现过程:
1、Clothes接口
public interface Clothes {
//设置衣服颜色
String setClothColor();
//设置衣服价格
float getPrice();
}
2、ConcreteCloth类
public String setClothColor() {
return "白色衣服";
}
public float getPrice() {
return 50f;
}
3、接着就是装饰者类ColorDecorator
public abstract class ColorDecorator implements Clothes{
<span style="white-space:pre"> </span>private Clothes clothe;
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>public ColorDecorator(Clothes clothe) {
<span style="white-space:pre"> </span>this.clothe = clothe;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>public String setClothColor() {
<span style="white-space:pre"> </span>return clothe.setClothColor();
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>public float getPrice() {
<span style="white-space:pre"> </span>return clothe.getPrice();
<span style="white-space:pre"> </span>}
}
4、在装饰者类的基础上来创建具体的装饰者类:
RedClothe:
public class RedClothe extends ColorDecorator{
public RedClothe(Clothes clothe) {
super(clothe);
}
public String setClothColor() {
return super.setClothColor()+"+红色";
}
public float getPrice() {
return super.getPrice()+120f;
}
}
public class GreenClothe extends ColorDecorator{
public GreenClothe(Clothes clothe) {
super(clothe);
}
public String setClothColor() {
return super.setClothColor()+"+绿色";
}
public float getPrice() {
return super.getPrice()+100f;
}
}
装饰者模式的代码已经,现在在说说这样做有什么好处,先假设不
用装饰者模式,我们一般会用什么方式来实现,多种颜色的组合呢?
比较直接的办法就是通过类继承的方式实现多种颜色的组合,但是
用这种方式,每一次产生一个特定的颜色组合时都会产生一个类,
这样就会导致,一个工程里面类的个数过于繁多,这样会导致很多
其他的问题,比如代码的可读性下降,而且会很大程度影响程序的
效率;而装饰者模式就解决了这个问题,通过装饰者这个类,可以
实现任意颜色的组合,这样就大大的减少了类的数量。
总结起来就一句话,装饰者模式比类继承更加灵活,效率更高。