设计模式之装饰者模式
装饰模式 对新房进行装修并没有改变房屋的本质,但它可以让房子变得更漂亮、更温馨、更实用。 在软件设计中,对已有对象(新房)的功能进行扩展(装修)。 把通用功能封装在装饰器中,用到的地方进行调用。 装饰模式是一种用于替代继承的技术,使用对象之间的关联关系取代类之间的继承关系。引入装饰类,扩充新功能。 角色 抽象构件 具体构件 抽象装饰类 具体装饰类
1.组件类
package Decorator; // 装饰者模式 /** * Created by Jiqing on 2016/10/13. */ abstract class Component { public abstract void display(); }
2.组件装饰者
package Decorator; /** * Created by Jiqing on 2016/10/13. */ public class ComponentDecorator extends Component{ private Component component; // 维持对抽象构件类型对象的引用 public ComponentDecorator(Component component){ this.component = component; } public void display() { component.display(); } }
3.继承类ListBox
package Decorator; /** * Created by Jiqing on 2016/10/13. */ public class ListBox extends Component{ public void display() { System.out.println("显示列表框!"); } }
4.继承类TextBox
package Decorator; /** * Created by Jiqing on 2016/10/13. */ public class TextBox extends Component{ public void display() { System.out.println("显示文本框!"); } }
5.继承类Window
package Decorator; /** * Created by Jiqing on 2016/10/13. */ public class Window extends Component{ public void display() { System.out.println("显示窗体!"); } }
6.黑框装饰者
package Decorator; /** * Created by Jiqing on 2016/10/14. */ public class BlackBoarderDecorator extends ComponentDecorator{ public BlackBoarderDecorator(Component component) { super(component); } public void display() { this.setBlackBoarder(); super.display(); } public void setBlackBoarder() { System.out.println("为构件增加黑色边框!"); } }
7.滚动条装饰者
package Decorator; /** * Created by Jiqing on 2016/10/14. */ public class ScrollBarDecorator extends ComponentDecorator{ public ScrollBarDecorator (Component component) { super(component); // 调用父类构造函数 } public void display() { this.setScrollBar(); super.display(); } public void setScrollBar() { System.out.println("为构件增加滚动条!"); } }
8.客户端调用
package Decorator; // 装饰者模式 /** * Created by Jiqing on 2016/10/14. */ public class Client { public static void main(String args[]) { Component component,componentSB,componentBB; component = new Window(); componentSB = new ScrollBarDecorator(component); componentSB.display(); System.out.println("--------------------"); componentBB = new BlackBoarderDecorator(componentSB); componentBB.display(); } }
执行结果
为构件增加滚动条!
显示窗体!
--------------------
为构件增加黑色边框!
为构件增加滚动条!
显示窗体!