装饰者模式【结构模式】

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;
    }
    }

posted on 2018-12-23 13:51  竺旭东  阅读(97)  评论(0编辑  收藏  举报

导航