欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java设计模式系列之装饰者模式

程序员文章站 2024-03-09 10:34:59
何为装饰者模式 (decorator)? 动态地给一个对象添加一些额外的职责。就增加功能来说,decorator 模式相比生成子类更为灵活。 一、结构 compo...

何为装饰者模式 (decorator)?
动态地给一个对象添加一些额外的职责。就增加功能来说,decorator 模式相比生成子类更为灵活。
一、结构

component : 定义一个对象接口,可以给这些对象动态地添加职责。

interface component {
  public void operation();
}
concretecomponent : 实现 component 定义的接口。
class concretecomponent implements component {
  @override
  public void operation() {
    system.out.println("初始行为");
  }
}

decorator : 装饰抽象类,继承了 component, 从外类来扩展 component 类的功能,但对于 component 来说,是无需知道 decorator 的存在的。

class decorator implements component {
  // 持有一个 component 对象,和 component 形成聚合关系
  protected component component;
  
  // 传入要进一步修饰的对象
  public decorator(component component) {
    this.component = component;
  }
  
  @override
  // 调用要修饰对象的原方法
  public void operation() {
    component.operation();
  }
}

concretedecorator : 具体的装饰对象,起到给 component 添加职责的功能。

class concretedecoratora extends decorator {
  private string addedstate = "新属性1";
  
  public concretedecoratora(component component) {
    super(component);
  }
  
  public void operation() {
    super.operation();
    system.out.println("添加属性: " + addedstate);
  }
}

class concretedecoratorb extends decorator {
  public concretedecoratorb(component component) {
    super(component);
  }

  public void operation() {
    super.operation();
    addedbehavior();
  }
  
  public void addedbehavior() {
    system.out.println("添加行为");
  }
}

测试代码

public class decoratorpattern {
  public static void main(string[] args) {
    component component = new concretecomponent();
    component.operation();
    
    system.out.println("======================================");
    decorator decoratora = new concretedecoratora(component);
    decoratora.operation();
    
    system.out.println("======================================");
    decorator decoratorb = new concretedecoratorb(decoratora);
    decoratorb.operation();
  }
}

运行结果

初始行为
======================================
初始行为
添加属性: 新属性1
======================================
初始行为
添加属性: 新属性1
添加行为

 二、应用场景

1、需要动态的、透明的为一个对象添加职责,即不影响其他对象。
2、需要动态的给一个对象添加功能,这些功能可以再动态的撤销。
3、需要增加由一些基本功能的排列组合而产生的非常大量的功能,从而使继承关系变的不现实。
4、当不能采用生成子类的方法进行扩充时。一种情况是,可能有大量独立的扩展,为支持每一种组合将产生大量的子类,使得子类数目呈爆炸性增长。另一种情况可能是因为类定义被隐藏,或类定义不能用于生成子类。

三、要点

1、装饰对象和真实对象有相同的接口。这样客户端对象就能以和真实对象相同的方式和装饰对象交互。

2、装饰对象包含一个真实对象的引用(reference)。

3、装饰对象接受所有来自客户端的请求。它把这些请求转发给真实的对象。

4、装饰对象可以在转发这些请求以前或以后增加一些附加功能。这样就确保了在运行时,不用修改给定对象的结构就可以在外部增加附加的功能。在面向对象的设计中,通常是通过继承来实现对给定类的功能扩展。

以上就是关于java装饰者模式的相关内容介绍,希望对大家的学习有所帮助。