Android 开发中的装饰者模式
1. 什么是装饰者模式?
装饰者模式(Decorator Pattern)是一种结构型设计模式,用于动态地给对象添加额外的职责,而无需修改对象本身。
这类似于在不改变手机的硬件设计下,通过安装保护壳或贴膜来增加功能。
2. 装饰者模式的核心组成部分
- Component(组件接口):定义了对象的核心行为,可以被装饰。
- ConcreteComponent(具体组件):实现了核心功能的类,被装饰者包裹。
- Decorator(装饰者):持有
Component的引用,扩展其行为。 - ConcreteDecorator(具体装饰者):实现扩展功能,增强
ConcreteComponent。
3. UML 类图

图示解释:
1. Component 是接口或抽象类,定义了基础功能。
2. ConcreteComponent 提供默认实现。
3. Decorator 抽象类,包装了 Component。
4. ConcreteDecoratorA/B 提供新的功能。
4. 代码示例:Android中动态添加功能
以 TextView 的扩展为例,比如为 TextView 动态添加边框或背景。
// Component: 定义核心功能
public interface View {
void draw();
}
// ConcreteComponent: 原始组件
public class TextView implements View {
@Override
public void draw() {
System.out.println("绘制TextView");
}
}
// Decorator: 装饰者抽象类
public abstract class ViewDecorator implements View {
protected View decoratedView;
public ViewDecorator(View decoratedView) {
this.decoratedView = decoratedView;
}
@Override
public void draw() {
decoratedView.draw();
}
}
// ConcreteDecorator: 添加边框功能
public class BorderDecorator extends ViewDecorator {
public BorderDecorator(View decoratedView) {
super(decoratedView);
}
@Override
public void draw() {
super.draw();
addBorder();
}
private void addBorder() {
System.out.println("添加边框");
}
}
// ConcreteDecorator: 添加背景功能
public class BackgroundDecorator extends ViewDecorator {
public BackgroundDecorator(View decoratedView) {
super(decoratedView);
}
@Override
public void draw() {
super.draw();
addBackground();
}
private void addBackground() {
System.out.println("添加背景");
}
}
// 使用示例
public class DecoratorDemo {
public static void main(String[] args) {
View textView = new TextView();
// 添加边框
View borderedTextView = new BorderDecorator(textView);
// 添加背景和边框
View styledTextView = new BackgroundDecorator(borderedTextView);
styledTextView.draw();
}
}
输出:
绘制TextView
添加边框
添加背景
5. 动画演示思路
可以通过以下方式直观展示装饰者模式:
1. 起点:绘制一个基本的 TextView。
2. 添加装饰:为 TextView 动态叠加边框动画。
3. 增强功能:为 TextView 增加背景颜色动画。
用 Android Animation Framework 实现:
val textView = findViewById<TextView>(R.id.myTextView)
// 动态添加边框动画
val borderAnimator = ObjectAnimator.ofFloat(textView, "alpha", 0f, 1f)
borderAnimator.duration = 1000
// 动态改变背景色动画
val backgroundAnimator = ObjectAnimator.ofArgb(
textView,
"backgroundColor",
Color.WHITE,
Color.YELLOW
)
backgroundAnimator.duration = 1000
// 按顺序播放动画
AnimatorSet().apply {
playSequentially(borderAnimator, backgroundAnimator)
start()
}
6. Android 中的实际应用
- RecyclerView 装饰器:通过
ItemDecoration为列表项添加分割线或边框。 - Glide 的图片处理链:动态添加变换(如圆角、模糊)。
- ConstraintLayout 的动态子视图增强:在运行时为子视图添加特效。
7. 总结与记忆技巧
装饰者模式就像是给对象“穿衣服”,基础功能是底层的衣服,装饰器是附加的外套。
记忆口诀:核心功能+叠加功能=增强的对象
当前文章价值3.85元,扫一扫支付后添加微信提供帮助!(如不能解决您的问题,可以申请退款)

你可能感兴趣的文章
分类:设计模式
标签:Android装饰者, 装饰者设计模式
评论已关闭!