装饰器模式,英文为 decorator模式

场景

假设我们已经有了一个类,可以执行一些功能,但是我们还是希望对这个类的功能做一些增强,基于已有类的功能上,再做一些增强功能,可以做装饰

不使用模式

package com.zhss.designpattern.decorator;

public class DecoratorPatternDemo {
	
	public static void main(String[] args) {
		Component component = new ConcreteComponent();
		Component decorator = new Decorator(component);
		decorator.execute();
	}
	
	public interface Component {
		
		void execute();
		
	}
	
	public static class ConcreteComponent implements Component {
		
		public void execute() {
			System.out.println("执行基础功能");
		}
		
	}	
}

使用模式

//其实就是多增加了这个方法
	public static class Decorator implements Component {

		private Component component;
		
		public Decorator(Component component) {
			this.component = component;
		}
		
		public void execute() {
			System.out.println("在执行基础功能之前,执行部分功能增强"); 
			component.execute();
			System.out.println("在执行基础功能之后,执行部分功能增强");  
		}
		
	}

经典实现

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