设计模式 -> 策略模式(Strategy Pattern)

前言

在Android开发中,策略模式是一种常用的设计模式,它能够让我们在运行时动态选择算法或行为。本文将重点介绍如何在Android中安全地实现策略模式,避免内存泄漏问题。

传统策略模式的问题

kotlin 复制代码
// ❌ 存在内存泄漏风险的实现
object LazyStart : StartStrategy {
    override operator fun invoke(block: suspend () -> Unit) {
        GlobalScope.launch {
            delay(1000)  
            // 延迟执行可能导致内存泄漏,block表达式持有的Activity/Fragment可能销毁后再执行,导致Activity/Fragment无法被GC
            block()
        }
    }
}

// 危险使用场景
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        LazyStart {
            updateUI()  // Activity可能已销毁,但lambda仍被执行
        }
    }
}

✅ 内存安全的解决方案

方案1:Class实现 + 作用域绑定

kotlin 复制代码
class SafeImmediateStart(private val scope: CoroutineScope) : StartStrategy {
    override operator fun invoke(block: suspend () -> Unit) {
        scope.launch {
            block()
        }
    }
}

class SafeLazyStart(private val scope: CoroutineScope) : StartStrategy {
    override operator fun invoke(block: suspend () -> Unit) {
        scope.launch {
            delay(1000)
            block()
        }
    }
}

// 安全使用
class MainActivity : AppCompatActivity() {
    private val immediateStrategy = SafeImmediateStart(lifecycleScope)
    private val lazyStrategy = SafeLazyStart(lifecycleScope)
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        immediateStrategy {
            updateUI()  // 安全:Activity销毁时协程自动取消
        }
    }
}

方案2:枚举实现 + 作用域绑定

kotlin 复制代码
enum class SafeStartStrategy {
    IMMEDIATE {
        override fun execute(scope: CoroutineScope, block: suspend () -> Unit) {
            scope.launch { block() }
        }
    },
    
    LAZY {
        override fun execute(scope: CoroutineScope, block: suspend () -> Unit) {
            scope.launch {
                delay(1000)
                block()
            }
        }
    };
    
    abstract fun execute(scope: CoroutineScope, block: suspend () -> Unit)
    
    operator fun invoke(scope: CoroutineScope, block: suspend () -> Unit) {
        execute(scope, block)
    }
}

// 使用方式
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        SafeStartStrategy.LAZY(lifecycleScope) {
            updateUI()
        }
    }
}

实际应用场景

kotlin 复制代码
// 内存安全检查清单
class MemorySafeStrategy(
    private val scope: CoroutineScope  // ✅ 1. 绑定正确作用域
) : StartStrategy {
    override operator fun invoke(block: suspend () -> Unit) {
        scope.launch {  // ✅ 2. 使用传入的scope
            try {
                block()
            } catch (e: CancellationException) {
                // ✅ 3. 处理取消异常
                Log.d("Strategy", "Execution cancelled")
            }
        }
    }
}

核心总结

场景 推荐方案 原因
UI操作 Class + lifecycleScope 绑定Activity生命周期
数据处理 Class + viewModelScope 绑定ViewModel生命周期
简单工具 改进枚举 + scope参数 简洁且安全
相关推荐
whitelbwwww32 分钟前
CUDA C++实战--中级
开发语言·前端·c++
好的佩奇1 小时前
Dart 之元数据与注解
android·flutter·dart
FungLeo1 小时前
FengCMS · PHP+MySQL 升级实录 · 内容写入一致性:锁等待超时与跨模型子树删除竞态
开发语言·mysql·php·工程实践·fengcms
三少爷的鞋2 小时前
很多开发者把物理上的分层,当成了架构
android
谙弆悕博士3 小时前
多智能体架构详解:市场拍卖式架构(Market-based / 竞价协商)
开发语言·架构·去中心化·多智能体·智能体·拍卖架构
ShineWinsu3 小时前
对于Qt:QMessageBox的解析
开发语言·c++·qt·面试·客户端·qmessagebox·消息对话框
承渊政道3 小时前
【Python编程快速上手—让繁琐工作自动化】(列表:把数据排成队,从下标取值到深拷贝)
开发语言·python·pycharm·自动化·列表
FungLeo3 小时前
FengCMS · PHP+MySQL 升级实录 · MySQL DDL不能回滚:模型字段结构操作的失败续做
android·mysql·php·工程实践·fengcms
雨白4 小时前
Android 建造者模式实战:从 AlertDialog 源码到 TopBar 的两种实现
android
tryCbest4 小时前
Python 爬虫从入门到实战(一):基础篇——从零写出第一个爬虫
开发语言·爬虫·python