【设计模式】Spring Boot中实践装饰模式

定义抽象Conponent

public interface HelloComponent {

    String hello();
}

实现Conponent

public class HelloComponentImpl implements HelloComponent {
    @Override
    public String hello() {
        return "Hello";
    }
}

定义Decorator

public abstract class HelloDecorator implements HelloComponent{
    protected HelloComponent helloComponent;

    public HelloDecorator(HelloComponent helloComponent){
        this.helloComponent = helloComponent;
    }
}

实现多种Decorator

Decorator实现方法一

public class LowerHelloDecorator extends HelloDecorator {
    public LowerHelloDecorator(HelloComponent helloComponent) {
        super(helloComponent);
    }

    @Override
    public String hello() {
        return this.helloComponent.hello().toLowerCase();
    }
}

Decorator实现方法二

public class UpperHelloDecorator extends HelloDecorator {
    public UpperHelloDecorator(HelloComponent helloComponent) {
        super(helloComponent);
    }

    @Override
    public String hello() {
        return this.helloComponent.hello().toUpperCase();
    }
}

创建Bean用于测试

@Configuration
public class MultiBeanConf {

    @Bean(name = "baseHello")
    HelloComponent baseHelloComponent(){
        return new HelloComponentImpl();
    }

    @Bean(name = "upperHello")
    HelloDecorator upperHelloDecorator(@Qualifier("baseHello") final HelloComponent helloComponent){
        return new UpperHelloDecorator(helloComponent);
    }

    @Bean(name = "lowerHello")
    HelloDecorator lowerHelloDecorator(@Qualifier("baseHello") final HelloComponent helloComponent){
        return new LowerHelloDecorator(helloComponent);
    }
}

测试

@SpringBootTest
class DecoratorApplicationTests {

	@Resource(name = "baseHello")
	HelloComponent baseHello;

	@Resource(name = "lowerHello")
	HelloDecorator lowerHello;

	@Resource(name = "upperHello")
	HelloDecorator upperHello;

	@Test
	void helloTests() {
		System.out.println(baseHello.hello());
		System.out.println(lowerHello.hello());
		System.out.println(upperHello.hello());

	}

}

代码地址

github

参考资料

  • https://blog.tratif.com/2018/04/12/decorating-spring-components/
  • https://stackoverflow.com/questions/54841554/how-to-implement-decorator-pattern-in-spring-boot
  • https://www.jianshu.com/p/8f6ebeee1ae6

版权声明:本文为hello_zxx原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。