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

  • 相关阅读:
    element树形控件单选
    字节一面:说说var、let、const之间的区别
    k8s之deployment应用
    Cesium关于Entity中的parent、isShowing、entityCollection和监听事件的探讨
    java读写锁
    二进制安装docker
    Go 封装http请求包Get、Post
    Win32 位图直接绘制
    react中useState的值没有改变,而是旧的数值
    【远程软件安装记录】——nomachnine、todesk、向日葵、等远程软件在ubuntu中的安装教程
  • 原文地址:https://blog.csdn.net/xcg340123/article/details/136207184