陕西网站设计,高端网站设计公司名单,wordpress中文版去广告,静态网页简单模板装饰器设计模式允许在运行时将附加职责或行为动态附加到对象。 它是一种结构模式#xff0c;利用聚合来组合这些行为。 在本教程中#xff0c;我们将学习实现装饰器模式。 UML图#xff1a; 让我们从装饰器模式的UML表示开始#xff1a; ConcreteComponent类是我们希望为… 装饰器设计模式允许在运行时将附加职责或行为动态附加到对象。 它是一种结构模式利用聚合来组合这些行为。 在本教程中我们将学习实现装饰器模式。 UML图 让我们从装饰器模式的UML表示开始 ConcreteComponent类是我们希望为其在运行时添加其他行为的类。 ConcreteDecorator1 ConcreteDecorator2 …是装饰器类它们包含装饰给定Component的逻辑。 请注意 抽象 Decorator类具有 组件。 换句话说它聚合了任何其他类型的组件这使我们可以将一个组件堆叠在另一个组件的顶部。 此外 ConcreteComponent和Decorator类都实现一个公共接口Component 。 示例实现 假设我们正在销售礼品。 一旦用户选择了礼物项目就有多种方法可以用红色或蓝色丝带紫色或绿色礼物包装纸等装饰该礼物项目。 与其为每个可能的组合创建一个类不如使用装饰器模式来实现它。 因此让我们创建我们的GiftComponent接口 public interface GiftComponent { void pack(); } 此外让我们编写GiftItem类这是GiftComponent的具体实现 public class GiftItem implements GiftComponent { public void pack() { System.out.println( Putting it in a box ); } } 实现抽象装饰器 现在我们有一个GiftItem我们会喜欢装饰让我们来定义抽象GiftDecorator类 public abstract AbstractGiftDecorator implements GiftComponent { protected GiftComponent gift; public AbstractGiftDecorator(GiftComponent gift) { this .gift gift; } public void pack() { this .gift.pack(); } } 礼物装饰器具有礼物组件的单个实例。 这样就可以将装饰器彼此堆叠。 创建多个装饰器 最后我们可以根据需要创建任意数量的自定义装饰器。 让我们创建一些礼品包装 public class PurpleWrapper extends AbstractGiftDecorator { public PurpleWrapper(GiftComponent gift) { super (gift); } public void pack() { super .pack(); System.out.println( Purple wrapper ); } } public class RedWrapper extends AbstractGiftDecorator { public RedWrapper(GiftComponent gift) { super (gift); } public void pack() { super .pack(); System.out.println( Red wrapper ); } } 以及几种用于进一步装饰的色带 public class BlueRibbon extends AbstractDecorator { public BlueRibbon(GiftComponent gift) { super (gift); } public void pack() { super .pack(); System.out.println( Blue ribbon ); } } public class PinkRibbon extends AbstractDecorator { public PinkRibbon(GiftComponent gift) { super (gift); } public void pack() { super .pack(); System.out.println( Pink Ribbon ); } } 测试我们的实施 现在让我们测试一下实现看看会发生什么 // client code GiftComponent gift new GiftItem(); GiftComponent giftWithPurpleWrapper new PurpleWrapper(gift); GiftComponent giftWithPurpleWrapperAndPinkRibbon new PinkRibbon(giftWithPurpleWrapper); giftWithPurpleWrapperAndPinkRibbon.pack(); 如我们所见我们现在可以通过链接装饰器轻松优雅地按照我们想要的方式包装礼品。 上面的代码将打印 Putting it in a box Purple Wrapper Pink Ribbon 结论 装饰器设计模式使用聚合来代替纯继承。 它允许我们向对象动态添加行为。 它消除了为每种可能的组合创建单独的类的开销从而大大减少了类的数量。 而且它遵循单一责任原则 该原则规定每个班级必须准确地做一件事。 使用装饰器设计模式设计java.io.BufferedReaderjava.io.FileReader之类的类 。 翻译自: https://www.javacodegeeks.com/2019/09/decorator-design-pattern-in-java.html