public String getDescription();
}
无滚动条功能的简单窗口实现
public class SimpleWindow implements Window {
@Override
public void draw() {
// 绘制窗口
}
@Override
public String getDescription() {
return “simple window”;
}
}
以下类包含所有Window类的decorator,以及修饰类本身。
// 抽象装饰类 注意实现Window接口
public abstract class WindowDecorator implements Window {
// 被装饰的Window
protected Window decoratedWindow;
public WindowDecorator (Window decoratedWindow) {
this.decoratedWindow = decoratedWindow;
}
@Override
public void draw() {
decoratedWindow.draw();
}
@Override
public String getDescription() {
return decoratedWindow.getDescription();
}
}
// 第一个具体装饰器 添加垂直滚动条功能
public class VerticalScrollBar extends WindowDecorator {
public VerticalScrollBar(Window windowToBeDecorated) {
super(windowToBeDecorated);
}
@Override
public void draw() {
super.draw();
drawVerticalScrollBar();
}
private void drawVerticalScrollBar() {
// Draw the vertical scrollbar
}
@Override
public String getDescription() {
return super.getDescription() + “, including vertical scrollbars”;
}
}
// 第二个具体装饰器 添加水平滚动条功能
public class HorizontalScrollBar extends WindowDecorator {
public HorizontalScrollBar (Window windowToBeDecorated) {
super(windowToBeDecorated);
}
@Override
public void draw() {
super.draw();
drawHorizontalScrollBar();
}
private void drawHorizontalScrollBar() {
// Draw the horizontal scrollbar
}
@Override
public String getDescription() {
return super.getDescription() + “, including horizontal scrollbars”;
}
}
=================================================================
使用装饰模式来实现扩展比继承更加灵活,它以对客户透明的方式动态地给一个对象附加更多的责任。装饰模式可以在不需要创造更多子类的情况下,将对象的功能加以扩展。
与继承相比,关联关系的优势在于不破坏类的封装性,而且继承是一种耦合度较大的静态关系,无法在程序运行时动态扩展。
可通过动态方式扩展一个对象的功能,通过配置文件可以在运行时选择不同装饰器,从而实现不同行为。
在软件开发阶段,关联关系虽然不会比继承关系减少编码量,但到了软件维护阶段,由于关联关系使系统具有较好的松耦合性,所以更容易维护。
通过使用不同具体装饰类以及这些装饰类的排列组合,可以创造出很多不同行为的组合。可以使用多个具体装饰类来装饰同一对象,得到功能更强大的对象。
具体构件类与具体装饰类可以独立变化,用户可以根据需要增加新的具体构件类、具体装饰类,在使用时再对其进行组合,原有代码无须改变,符合“开闭原则”。
=================================================================
最后
文章中涉及到的知识点我都已经整理成了资料,录制了视频供大家下载学习,诚意满满,希望可以帮助在这个行业发展的朋友,在论坛博客等地方少花些时间找资料,把有限的时间,真正花在学习上,所以我把这些资料,分享出来。相信对于已经工作和遇到技术瓶颈的朋友们,在这份资料中一定都有你需要的内容。