1. 概念
指在不改变现有对象结构的情况下,动态地给该对象增加一些职责(即增加其额外功能)的模式,它属于对象结构型模式。
2. 优点
- 装饰器是继承的有力补充,比继承灵活,在不改变原有对象的情况下,动态的给一个对象扩展功能,即插即用。
- 通过使用不同装饰类及这些装饰类的排列组合,可以实现不同效果
- 装饰器模式完全遵守开闭原则
3. 缺点
装饰器模式会增加许多子类,过度使用会增加程序的复杂性。
4. 结构与实现
通常情况下,扩展一个类的功能会使用继承方式来实现。但继承具有静态特征,耦合度高,并且随着扩展功能的增多,子类会很膨胀。如果使用组合关系来创建一个包装对象(即装饰对象),并在保持真实对象的类结构不变的前提下,为其提供额外的功能,这就是装饰器模式的目标。
4.1 结构
主要角色:
- 抽象构件角色:定义一个抽象接口以规范准备接受附加责任的对象。
- 具体构件角色:实现抽象构件角色为其添加一些职责。
- 抽象装饰角色:继承抽象构件,并包含具体构件的实例,可以通过其子类扩展具体构件的功能。
- 具体装饰角色:实现抽象装饰的相关方法,并给具体构件对象添加附加的责任。
4.2 实现
//抽象构件角色
public interface Component {
void operation();
}
//抽象装饰角色
public abstract class Decorator implements Component {
private Component component;
public Decorator(Component component) {
this.component = component;
}
@Override
public void operation() {
component.operation();
}
}
//具体构件角色 床
public class Bed implements Component{
@Override
public void operation() {
System.out.println("我是一个用来睡觉的床");
}
}
//具体装饰器 放枕头
public class Pillow extends Decorator {
public Pillow(Component component) {
super(component);
}
@Override
public void operation() {
super.operation();
addedFunction();
}
private void addedFunction() {
System.out.println("放上枕头");
}
}
//具体装饰器 放被子
public class Quilt extends Decorator {
public Quilt(Component component) {
super(component);
}
@Override
public void operation() {
super.operation();
addedFunction();
}
private void addedFunction() {
System.out.println("放上被子");
}
}
测试
public class DecoratorTest {
@Test
public void test1() {
Bed newBed = new Bed();
//在床上放枕头
Pillow pillow = new Pillow(newBed);
pillow.operation();
//在床上放被子
Quilt quilt = new Quilt(newBed);
quilt.operation();
//在床上放上枕头和被子
Pillow pillowQuit1 = new Pillow(newBed);
Quilt pillowQuit2 = new Quilt(pillowQuit1);
pillowQuit2.operation();
}
}