1,什么是装饰者模式
装饰者模式就是在不修改当前类的前提下向现有对象添加新功能,通过包装类来提供额外的功能。
2,关键对象
-
抽象被装饰类(接口或抽象类):用于规范接口或方法定义
-
被装饰类:方法源,通过装饰者为其添加方法
-
抽象装饰者(非必要):继承抽象构建,并包含装饰类,通过子类来进行具体扩展
-
具体装饰者:实现抽象构建的方法,并进行扩展,添加新功能或修改原方法的具体实现
3,示例
装饰者模式是较为简单的结构型设计模式,主要为了扩展类功能,如果仔细琢磨装饰者模式,是有点类似于代理模式的;
package decorator;
public class DecoratorPattern {
public static void main(String[] args) {
Component p = new ConcreteComponent();
p.operation();
System.out.println("---------------------------------");
Component d = new ConcreteDecorator(p);
d.operation();
}
}
//抽象被装饰类
interface Component {
public void operation();
}
//具体被装饰者
class ConcreteComponent implements Component {
public ConcreteComponent() {
System.out.println("具体被装饰者");
}
public void operation() {
System.out.println("调用具体被装饰者的方法------");
}
}
//抽象装饰者(可省略)
class Decorator implements Component {
private Component component;
public Decorator(Component component) {
this.component = component;
}
public void operation() {
component.operation();
}
}
//具体装饰者
class ConcreteDecorator extends Decorator {
public ConcreteDecorator(Component component) {
super(component);
}
public void operation() {
super.operation();
System.out.println("为具体装饰者增加额外的功能------");
}
}
4,关注点
通过组合的方式来实现了功能的扩展,而不是使用继承,避免了继承带来的强耦合。但是随着功能的增多,装饰者也会产生类膨胀的现象。
5,实践中的装饰者模式
1,Mybatis源码缓存架构
Mybatis的缓存架构就是使用了较多的装饰类实现了不同场景下的缓存实现,具体如下
2,java IO流类模块
如:
Reader == 被装饰者,BufferedReader == 装饰者;
InputStream == 被装饰者,BufferedInputStream == 装饰者;