加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

装饰者模式【结构模式】

发布时间:2020-12-14 04:26:25 所属栏目:大数据 来源:网络整理
导读:public class Decorator { /** * 装饰者模式: * Attach additional responsibility to an object dynamically keeping the same interface. * Decorators provide a flexible alternative to subclassing for extending functionality. * 将额外的责任附加

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("rn",title,info),make);

    final String copyRight = "版权所有 15505883728";
    // 给新闻增加版权
    final CopyRightMaker copyRightMaker = CopyRightMaker.builder()
            .newsMaker(titleMaker)
            .copyRight(copyRight)
            .build();
    make = copyRightMaker.make(info);
    assertEquals(String.join("rn",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 + "rn" + 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) + "rn" + copyRight; } }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读