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

网友投稿 186 2023-07-22


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

何为装饰者模式 (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;

}

@Overrhttp://ide

// 调用要修饰对象的原方法

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装饰者模式的相关内容介绍,希望对大家的学习有所帮助。


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:理解java设计模式之建造者模式
下一篇:理解java和python类变量以及类的成员变量
相关文章

 发表评论

暂时没有评论,来抢沙发吧~