Java设计模式–装饰器模式
- 定义
在不改变原有对象的基础上 将功能附加到对象上
- 实现
public class DecoratorTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Component component=new ConreteDecorator2(new ConreteDecorator(new ConcreteComponent()));
component.operation();
}
}
interface Component{
void operation();
}
class ConcreteComponent implements Component{
@Override
public void operation() {
// TODO Auto-generated method stub
System.out.println("拍照");
}
}
abstract class Decorator implements Component{
Component component;
public Decorator(Component component) {
this.component=component;
}
}
class ConreteDecorator extends Decorator{
public ConreteDecorator(Component component) {
super(component);
// TODO Auto-generated constructor stub
}
@Override
public void operation() {
System.out.println("添加美颜");
component.operation();
}
}
class ConreteDecorator2 extends Decorator{
public ConreteDecorator2(Component component) {
super(component);
// TODO Auto-generated constructor stub
}
@Override
public void operation() {
System.out.println("添加滤镜");
component.operation();
}
}
- 应用场景
-
扩展一个类的功能或给一个类添加附加职责 - 优点
-
1.不改变原有对象的情况下给一个对象扩展功能 2.使用不同的组合可以实现不同的效果 3.符合开闭原则 - 经典实例
-
Servlet Api: javax.servlet.http.HttpServletRequestWrapper javax.servlet.http.HttpServletResponseWrapper
本文详细介绍了Java设计模式中的装饰器模式,通过具体代码示例展示了如何在不修改原始对象的前提下为其添加新功能,适用于扩展类功能或增加职责场景。文章深入探讨了装饰器模式的实现原理和优势,并给出了Servlet API中装饰器模式的应用实例。
3056

被折叠的 条评论
为什么被折叠?



