3.0 KiB
3.0 KiB
装饰者模式
目录
装饰者模式概念
定义
// 装饰者模式:动态地给对象添加一些额外的职责
// 就增加功能来说,装饰者模式比生成子类更灵活
使用场景
// 1. 需要动态地给对象添加功能
// 2. 需要撤销功能
// 3. 使用继承会导致类爆炸
装饰者模式实现
基本实现
// 组件接口
public interface Component {
void operation();
}
// 具体组件
public class ConcreteComponent implements Component {
@Override
public void operation() {
System.out.println("Concrete Component");
}
}
// 装饰者抽象类
public abstract class Decorator implements Component {
protected Component component;
public Decorator(Component component) {
this.component = component;
}
@Override
public void operation() {
component.operation();
}
}
// 具体装饰者
public class ConcreteDecoratorA extends Decorator {
public ConcreteDecoratorA(Component component) {
super(component);
}
@Override
public void operation() {
super.operation();
addedBehavior();
}
private void addedBehavior() {
System.out.println("Added Behavior A");
}
}
// 使用
Component component = new ConcreteComponent();
Component decorated = new ConcreteDecoratorA(component);
decorated.operation();
装饰者模式应用
Android 中的应用
1. ContextWrapper
// ContextWrapper 是 Context 的装饰者
public class ContextWrapper extends Context {
Context mBase;
public ContextWrapper(Context base) {
mBase = base;
}
@Override
public void startActivity(Intent intent) {
mBase.startActivity(intent);
}
}
2. InputStream 装饰者
// Java IO 使用装饰者模式
InputStream is = new FileInputStream("file.txt");
BufferedInputStream bis = new BufferedInputStream(is);
DataInputStream dis = new DataInputStream(bis);
装饰者模式最佳实践
1. 保持接口一致
// 装饰者和被装饰者实现同一接口
// 可以透明地使用装饰者
2. 避免过度装饰
// 不要创建过多的装饰层
// 保持代码简洁
面试常见问题
Q1: 装饰者模式的原理?
答案:
- 动态地给对象添加额外的职责
- 比继承更灵活
Q2: 装饰者模式和代理模式的区别?
答案:
- 装饰者模式:增强功能,关注对象本身
- 代理模式:控制访问,关注访问控制
Q3: Android 中的装饰者模式应用?
答案:
- ContextWrapper:装饰 Context
- Java IO:InputStream 装饰者链
最后更新:2024年