装饰器模式可以使用聚合来组合运行时的行为。“聚合aggregation是将事物或数量组合为单个组或总计的过程”。聚合的同义词之一是“堆heap”,堆是“杂乱的堆或大量的东西”。我认为这个定义还可以。对我来说只有一件事毁了它。如果聚合是一个过程,而堆(一个不整洁的堆)是该过程的结果,那么为什么这两个词是同义词?
Java语言中的抽象
在Java中,聚合更为简单。这是由单向关联表示的类之间的关系。堆是聚合的体现。
看一看。这是一个对象。它具有类型和名称。它可以存在。
@Builder public class Thing { String type; String name; }
|
这是堆。它有一个高度(大堆/巨大……)和位置,但是没有Thing它就不可能存在。@Data public class Heap { private String height; private String location; private List<Thing> thing; }
|
仅当您拥有衣服之类的东西Thing时,您才能创建一堆heap衣服。扒开层层衣服并将它们不整洁地扔在地板上
public Heap createHeapOfClothes() { Heap heap = new Heap(); heap.setHeight("huge"); heap.setLocation("on the bathroom floor"); heap.setThing(Arrays.asList( Thing.builder().type("clothes").name("t-shirt").build(), Thing.builder().type("clothes").name("jeans").build(), Thing.builder().type("clothes").name("right sock").build(), Thing.builder().type("clothes").name("left sock").build())); return heap; }
|
我不只是提出聚合。装饰器模式可以使用聚合来组合运行时的行为。
装饰器模式
装饰器模式是一种设计模式,它允许动态地将行为添加到单个对象中,而不会影响同一类中其他对象的行为。这是一种结构模式,通过围绕对象构造包装来扩展其行为。考虑一下分层服装。每层都是装饰器,包装上一层。
基础类:
public class AutumnOutfit extends Outfit { @Override public void describeTop() { log.info("white sweater"); } @Override public void describeBottom() { log.info("ripped jeans"); } @Override public void describeFootwear() { log.info("veja sneakers"); } }
|
现在,您需要一个Outwear Decorator,以使用聚合将更多服装添加到基本服装中。您将需要使用抽象装饰器类的子类来添加到基本服装中。正如我们之前所探讨的,“服装装饰器”是“服装”的子类。因此,混凝土装饰师也是服装的子类。
@RequiredArgsConstructor public abstract class OuterwearDecorator extends Outfit { public abstract void describeOuterwear(); @Override public void createDailyLook() { describeTop(); describeBottom(); describeFootwear(); describeOuterwear(); drawDescribedOutfit(); cutDrawnOutfit(); } }
|
基本装饰器拥有新的抽象行为describeOuterwear(),它将由具体装饰器实现。并且,它覆盖了该createDailyLook()方法。
下一步是实现抽象方法。创建一个混凝土外套装饰器。
@RequiredArgsConstructor public class CoatDecorator extends OuterwearDecorator {
private final Outfit outfit;
@Override public void describeOuterwear() { log.info("camel coat");} @Override public void describeTop() { outfit.describeTop();} @Override public void describeBottom() { outfit.describeBottom();} @Override public void describeFootwear() { outfit.describeFootwear(); } }
|
装饰器类的行为就像实现抽象方法的另一个类一样。唯一的区别是,它聚合了基类。它将允许将一些行为堆叠在一起。
调用代码:
public void createAutumnOutfitWithCoat() { Outfit autumnOutfit = seasonOutfitFactory.createOutfit(Season.AUTUMN); autumnOutfit = new CoatDecorator(autumnOutfit); autumnOutfit.createDailyLook(); }
|
重要的是基本服装必须是堆heap中的第一件。接下来,将其包裹在外套装饰器中。然后调用该createDailyLook()方法,以绘制和剪切所描述的服装。您的抽象装饰器只需将每日外观创建委托给它聚合的Outfit对象。检查日志。运行结果:AutumnOutfit - white sweater AutumnOutfit - ripped jeans AutumnOutfit - veja sneakers CoatDecorator - camel coat Outfit - drawing outfit according to selections Outfit - cutting drawn outfit
|
这是这篇文章的git项目的链接