java设计模式系列之装饰者模式
何为装饰者模式(Decorator)?
动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。
一、结构
Component:定义一个对象接口,可以给这些对象动态地添加职责。
interfaceComponent{ publicvoidoperation(); } ConcreteComponent:实现Component定义的接口。 classConcreteComponentimplementsComponent{ @Override publicvoidoperation(){ System.out.println("初始行为"); } }
Decorator:装饰抽象类,继承了Component,从外类来扩展Component类的功能,但对于Component来说,是无需知道Decorator的存在的。
classDecoratorimplementsComponent{ //持有一个Component对象,和Component形成聚合关系 protectedComponentcomponent; //传入要进一步修饰的对象 publicDecorator(Componentcomponent){ this.component=component; } @Override //调用要修饰对象的原方法 publicvoidoperation(){ component.operation(); } }
ConcreteDecorator:具体的装饰对象,起到给Component添加职责的功能。
classConcreteDecoratorAextendsDecorator{ privateStringaddedState="新属性1"; publicConcreteDecoratorA(Componentcomponent){ super(component); } publicvoidoperation(){ super.operation(); System.out.println("添加属性:"+addedState); } } classConcreteDecoratorBextendsDecorator{ publicConcreteDecoratorB(Componentcomponent){ super(component); } publicvoidoperation(){ super.operation(); AddedBehavior(); } publicvoidAddedBehavior(){ System.out.println("添加行为"); } }
测试代码
publicclassDecoratorPattern{ publicstaticvoidmain(String[]args){ Componentcomponent=newConcreteComponent(); component.operation(); System.out.println("======================================"); DecoratordecoratorA=newConcreteDecoratorA(component); decoratorA.operation(); System.out.println("======================================"); DecoratordecoratorB=newConcreteDecoratorB(decoratorA); decoratorB.operation(); } }
运行结果
初始行为 ====================================== 初始行为 添加属性:新属性1 ====================================== 初始行为 添加属性:新属性1 添加行为
二、应用场景
1、需要动态的、透明的为一个对象添加职责,即不影响其他对象。
2、需要动态的给一个对象添加功能,这些功能可以再动态的撤销。
3、需要增加由一些基本功能的排列组合而产生的非常大量的功能,从而使继承关系变的不现实。
4、当不能采用生成子类的方法进行扩充时。一种情况是,可能有大量独立的扩展,为支持每一种组合将产生大量的子类,使得子类数目呈爆炸性增长。另一种情况可能是因为类定义被隐藏,或类定义不能用于生成子类。
三、要点
1、装饰对象和真实对象有相同的接口。这样客户端对象就能以和真实对象相同的方式和装饰对象交互。
2、装饰对象包含一个真实对象的引用(reference)。
3、装饰对象接受所有来自客户端的请求。它把这些请求转发给真实的对象。
4、装饰对象可以在转发这些请求以前或以后增加一些附加功能。这样就确保了在运行时,不用修改给定对象的结构就可以在外部增加附加的功能。在面向对象的设计中,通常是通过继承来实现对给定类的功能扩展。
以上就是关于java装饰者模式的相关内容介绍,希望对大家的学习有所帮助。