• 【设计模式】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()

  • 相关阅读:
    前端动画的另一种方式 json动画
    spring cloud 快速上手系列 -> 04-网关 Gateway -> 041-空的工程
    Java实用类(五) -Math类和指定范围的随机数
    寒气逼人的 2023 届秋招
    【powershell】入门和示例
    Java部分面试题(宝典篇)
    python渗透测试入门——基础的网络编程工具
    面试题:Java序列化与反序列化
    django: You may need to add ‘localhost‘ to ALLOWED_HOSTS
    影单:分享一下最近在看的一些电影
  • 原文地址:https://blog.csdn.net/xcg340123/article/details/136207184