decorator模式

场景

(1)假设我们手头已经有了一个类,可以执行一些功能 (2)但是我们还是希望对这个类的功能做一些增强,此时怎么办呢?基于已有的类的功能基础之上,再增强一些功能,可以做装饰

1.装饰器模式

  1. package com.example.demo.pattern.decorator;
  2. /**
  3. * @author chenchao
  4. * @date 2021/11/9
  5. */
  6. public class DecoratorPatternDemo {
  7. public static void main(String[] args) {
  8. Component component = new ConcreteComponent();
  9. Component decorator = new Decorator(component);
  10. decorator.execute();
  11. }
  12. public interface Component {
  13. void execute();
  14. }
  15. public static class ConcreteComponent implements Component {
  16. public void execute() {
  17. System.out.println("执行基础功能");
  18. }
  19. }
  20. public static class Decorator implements Component {
  21. private Component component;
  22. public Decorator(Component component) {
  23. this.component = component;
  24. }
  25. public void execute() {
  26. System.out.println("在执行基础功能之前,执行部分功能增强");
  27. component.execute();
  28. System.out.println("在执行基础功能之后,执行部分功能增强");
  29. }
  30. }
  31. }

2.说明

装饰器模式有一些非常经典的实现

(1)比如java的io体系,可以一层包装一层,一层包装一层,外面的一层,都会对立面的一层进行功能的增强。
(2)还有就是spring的aop,aop这块可以基于动态代理的理念,装饰我们的目标对象,然后加入事务控制,日志打印之类的功能。

1301584033