学习设计模式不光要学习设计模式的思想,还要去深入理解,为什么要用这个设计模式。
如何深入理解?读优秀的框架代码,看别人代码,了解它们的使用场景。 - - - 博主老师(感谢他)
本文先介绍了装饰器模式的概念及简单实现。再贴了netty中对装饰器模式的实现。最后总结了一点点思考。
装饰器模式-概念、实现及netty中的装饰器模式
1、概念
装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。
2、实现
我们考虑这么个例子:原始字体、给字体加粗、给字体倾斜
定义一个字体接口及其实现类
public interface IFont {
void show();
}
public class Font implements IFont {
@Override
public void show() {
System.out.print("我是原始的字体");
}
}
定义一个字体的包装类,持有字体接口,在构造方法传入,在show方法直接调用该对象的show方法
public class FontWrapper implements IFont{
private IFont iFont;
public FontWrapper(IFont iFont) {
this.iFont = iFont;
}
@Override
public void show() {
iFont.show();
}
}
定义粗体-继承包装类
public class BoldFont extends FontWrapper {
public BoldFont(IFont iFont) {
super(iFont);
}
@Override
public void show() {
System.out.print("我把你加粗(");
super.show();
System.out.print(")");
}
}
定义斜体-继承包装类
public class ItalicFont extends FontWrapper {
public ItalicFont(IFont iFont) {
super(iFont);
}
@Override
public void show() {
System.out.print("我把你倾斜(");
super.show();
System.out.print(")");
}
}
测试类
public class Test {
public static void main(String[] args) {
IFont font = new ItalicFont(new BoldFont(new Font()));
font.show();
}
}
输出
我把你倾斜(我把你加粗(我是原始的字体))
看上面的测试类代码是不是有中熟悉的感觉?
很像JavaIO中的某种写法:
Reader reader = new BufferedReader(new InputStreamReader(in , “UTF-8”));
是的,JAVA IO这也用的是装饰器模式
3、netty中的装饰器模式
BtypeBuf鼎鼎大名,我就不介绍了…与之相关的WrappedByteBuf实现了byteBuf的装饰
我们先看下WrappedByteBuf(类似于我们上面的FontWrapper)
class WrappedByteBuf extends ByteBuf {
...
protected final ByteBuf buf;
protected WrappedByteBuf(ByteBuf buf) {
this.buf = ObjectUtil.checkNotNull(buf, "buf");
}
@Override
public ByteBuf slice() {
return buf.slice();
}
...
}
持有一个byteBuf, 在具体的方法中调用byteBuf对应的方法
再看他的装饰器实现类SimpleLeakAwareByteBuf
class SimpleLeakAwareByteBuf extends WrappedByteBuf {
private final ByteBuf trackedByteBuf;
final ResourceLeakTracker<ByteBuf> leak;
SimpleLeakAwareByteBuf(ByteBuf wrapped, ByteBuf trackedByteBuf, ResourceLeakTracker<ByteBuf> leak) {
super(wrapped);
this.trackedByteBuf = ObjectUtil.checkNotNull(trackedByteBuf, "trackedByteBuf");
this.leak = ObjectUtil.checkNotNull(leak, "leak");
}
SimpleLeakAwareByteBuf(ByteBuf wrapped, ResourceLeakTracker<ByteBuf> leak) {
this(wrapped, wrapped, leak);
}
@Override
public ByteBuf slice() {
return newSharedLeakAwareByteBuf(super.slice());
}
}
除了SimpleLeakAwareByteBuf, netty中还提供了AdvancedLeakAwareByteBuf(),UnreleasableByteBuf(扩展阻止他人对byteBuf销毁的扩展)这两个子类。
4、思考
装饰器模式比较简单,博主理解,在我们需要对某个对象的功能进行扩展时,可以使用此模式。例如我们一开始中的例子,为字体做扩展(可以加粗,可以倾斜),而不是改变原来的Font类。netty要扩展byteBuf,而不是去改变byteBuf。byteBuf提供核心的缓冲区读写、copy等功能。而装饰器类再对这个缓冲区做扩展,例如实现阻止他人销毁byteBuf。感觉也有点effective java中提到的复合优先于继承的思想。