码迷,mamicode.com
首页 > 其他好文 > 详细

装饰者模式【结构模式】

时间:2018-12-23 15:19:49      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:标题   VID   \n   builder   news   额外   ons   extend   res   

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

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

装饰者模式【结构模式】

标签:标题   VID   \n   builder   news   额外   ons   extend   res   

原文地址:https://www.cnblogs.com/zhuxudong/p/10164119.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!