zoukankan      html  css  js  c++  java
  • 装饰者模式【结构模式】

    public class Decorator {
    /**
    * 装饰者模式:
    * Attach additional responsibility to an object dynamically keeping the same interface.
    * Decorators provide a flexible alternative to subclassing for extending functionality.
    * 将额外的责任附加到一个动态保持相同接口的对象上,装饰者提供一种灵活的选择将扩展功能子类化。
    */
    @Test
    public void all() {
    final PlainMaker plainMaker = PlainMaker.builder().build();
    final String info = "hello world";
    String make = plainMaker.make(info);
    assertEquals(make, info);

    	final String title = "重大新闻";
    	// 给新闻增加标题
    	final TitleMaker titleMaker = TitleMaker.builder()
    			.newsMaker(plainMaker)
    			.title(title).build();
    	make = titleMaker.make(info);
    	assertEquals(String.join("
    ", title, info), make);
    
    	final String copyRight = "版权所有 15505883728";
    	// 给新闻增加版权
    	final CopyRightMaker copyRightMaker = CopyRightMaker.builder()
    			.newsMaker(titleMaker)
    			.copyRight(copyRight)
    			.build();
    	make = copyRightMaker.make(info);
    	assertEquals(String.join("
    ", title, info, copyRight), make);
    }
    

    }

    /**

    • 1)定义允许执行装饰的功能接口,也可以是抽象类。
      */
      interface NewsMaker {
      String make(String info);
      }

    /**

    • 2)具体实现功能的实例类
      */
      @Builder
      class PlainMaker implements NewsMaker {
      @Override
      public String make(String info) {
      return info;
      }
      }

    /**

    • 3)对功能进行装饰的装饰类
      */
      @Builder
      class TitleMaker implements NewsMaker {
      private final NewsMaker newsMaker;
      private final String title;

      @Override
      public String make(String info) {
      return title + " " + newsMaker.make(info);
      }
      }

    /**

    • 4)对功能进行装饰的装饰类
      */
      @Builder
      class CopyRightMaker implements NewsMaker {
      private final NewsMaker newsMaker;
      private final String copyRight;

      @Override
      public String make(String info) {
      return newsMaker.make(info) + " " + copyRight;
      }
      }

  • 相关阅读:
    Spring cloud实现服务注册及发现
    使用spring cloud实现分布式配置管理
    spring cloud教程之使用spring boot创建一个应用
    7天学会spring cloud教程
    微服务开发的12项要素
    一句话概括下spring框架及spring cloud框架主要组件
    翻译-服务注册与发现
    翻译-微服务API Gateway
    微服务分布式事务的一些思考
    解决不能正常访问workerman的问题
  • 原文地址:https://www.cnblogs.com/zhuxudong/p/10164119.html
Copyright © 2011-2022 走看看