• 【设计模式】01-装饰器模式Decorator


    作用:在不修改对象外观和功能的情况下添加或者删除对象功能,即给一个对象动态附加职能

    装饰器模式主要包含以下角色。

    1. 抽象构件(Component)角色:定义一个抽象接口以规范准备接收附加责任的对象。
    2. 具体构件(ConcreteComponent)角色:实现抽象构件,通过装饰角色为其添加一些职责。
    3. 抽象装饰(Decorator)角色:继承抽象构件,并包含具体构件的实例,可以通过其子类扩展具体构件的功能。
    4. 具体装饰(ConcreteDecorator)角色:实现抽象装饰的相关方法,并给具体构件对象添加附加的责任。

    1. package decorator;
    2. public class DecoratorPattern {
    3. public static void main(String[] args) {
    4. Component p = new ConcreteComponent();
    5. p.operation();
    6. System.out.println("---------------------------------");
    7. Component d = new ConcreteDecorator(p);
    8. d.operation();
    9. }
    10. }
    11. //抽象构件角色
    12. interface Component {
    13. public void operation();
    14. }
    15. //具体构件角色
    16. class ConcreteComponent implements Component {
    17. public ConcreteComponent() {
    18. System.out.println("创建具体构件角色");
    19. }
    20. public void operation() {
    21. System.out.println("调用具体构件角色的方法operation()");
    22. }
    23. }
    24. //抽象装饰角色
    25. class Decorator implements Component {
    26. private Component component;
    27. public Decorator(Component component) {
    28. this.component = component;
    29. }
    30. public void operation() {
    31. component.operation();
    32. }
    33. }
    34. //具体装饰角色
    35. class ConcreteDecorator extends Decorator {
    36. public ConcreteDecorator(Component component) {
    37. super(component);
    38. }
    39. public void operation() {
    40. super.operation();
    41. addedFunction();
    42. }
    43. public void addedFunction() {
    44. System.out.println("为具体构件角色增加额外的功能addedFunction()");
    45. }
    46. }

    运行结果

    1. 创建具体构件角色
    2. 调用具体构件角色的方法operation()
    3. ---------------------------------
    4. 调用具体构件角色的方法operation()
    5. 为具体构件角色增加额外的功能addedFunction()

  • 相关阅读:
    数论练习题
    计算机毕业设计springboot基于微信小程序的汇客源民宿预订平台
    【Maven】Could not transfer artifact xxx from/to xxx的解决方案
    centos7快速搭建ftp服务器
    SpringBoot保姆级教程(四)YAML文件
    轻松上手的VsCode:你的理想代码编辑器!
    原理图合并中的技巧
    P1381 单词背诵【双指针】
    【Redis】基础数据结构-quicklist
    计算机基础
  • 原文地址:https://blog.csdn.net/xcg340123/article/details/136207184