一、为什么需要设计模式?
在软件开发中,设计模式是经过验证的解决方案,能够帮助我们写出可维护、可扩展、可测试的代码。在 Android 视频播放器开发中,合理运用设计模式尤为重要:
- 解码器可能更换:MediaCodec、FFmpeg、ExoPlayer
- 帧处理方式多样:YUV转换、滤镜处理、缩放裁剪
- 状态管理复杂:播放、暂停、停止、错误处理
二、工厂模式
场景:创建不同类型的解码器
java
public class DecoderFactory {
public enum DecoderType {
MEDIA_CODEC,
FFMPEG,
EXO_PLAYER
}
private final Context context;
public DecoderFactory(Context context) {
this.context = context.getApplicationContext();
}
public VideoDecoder createDecoder(DecoderType type, int maxImages) {
switch (type) {
case MEDIA_CODEC:
return new MediaCodecDecoder(context, maxImages);
case FFMPEG:
return new FFmpegDecoder(context, maxImages);
default:
throw new IllegalArgumentException("Unknown decoder type: " + type);
}
}
}
优势:
- 解耦创建逻辑与使用逻辑
- 新增解码器只需扩展枚举和 switch 分支
- 符合开闭原则
三、策略模式
场景:不同的帧处理策略
java
public interface FrameProcessor {
VideoFrame process(Image image);
void release();
}
public class YuvFrameProcessor implements FrameProcessor {
@Override
public VideoFrame process(Image image) {
// YUV -> ABGR -> Bitmap
}
}
public class FilterFrameProcessor implements FrameProcessor {
@Override
public VideoFrame process(Image image) {
// 带滤镜处理
}
}
优势:
- 处理算法可随时替换
- 运行时动态切换处理策略
- 每个策略独立测试
四、建造者模式
场景:构建复杂的视频源配置
java
VideoSource source = new VideoSource.Builder()
.setFileName("video.mp4")
.setWidth(1920)
.setHeight(1080)
.setType(VideoSource.SourceType.ASSET)
.build();
优势:
- 参数可选、有序
- 链式调用,代码可读性强
- 构建逻辑封装在 Builder 内部
五、观察者模式
场景:播放状态变化通知 UI 更新
java
public class VideoPlayerViewModel extends ViewModel {
private final MutableLiveData<PlayerState> playerState = new MutableLiveData<>();
public LiveData<PlayerState> getPlayerState() {
return playerState;
}
}
// Activity 中观察
viewModel.getPlayerState().observe(this, state -> {
updateButtonState(state);
});
优势:
- UI 与业务逻辑完全解耦
- LiveData 自动管理生命周期
- 数据驱动 UI 更新
六、总结
| 设计模式 | 应用场景 | 核心价值 |
|---|---|---|
| 工厂模式 | 解码器创建 | 解耦创建与使用 |
| 策略模式 | 帧处理算法 | 算法可替换 |
| 建造者模式 | 配置对象构建 | 参数灵活、可读性强 |
| 观察者模式 | 状态通知 | 数据驱动 UI |