设计模式 -> 策略模式(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参数 简洁且安全
相关推荐
白仑色1 分钟前
JavaScript案例(乘法答题游戏)
开发语言·javascript·游戏
深盾安全10 分钟前
Android SO导出符号的深度解析与安全防护指南
android
顾林海31 分钟前
Android安全防护:Runtime 调试检测与反制手段
android·安全·面试
什么半岛铁盒36 分钟前
MySQL 约束知识体系:八大约束类型详细讲解
android·数据库·mysql
一个会的不多的人1 小时前
C# NX二次开发:超级点控件使用详解
开发语言·c#
丐中丐9991 小时前
Android系统中如何在Native层调用java实现的系统服务
android·操作系统
stringwu1 小时前
Flutter plugin开发小知识之:ActivityAware 详解
android
whysqwhw1 小时前
Matrix.setPolyToPoly() 函数使用指南
android
丐中丐9991 小时前
在Android中利用抽象类对外提供系统接口
android·操作系统
weixin_437499921 小时前
【PHP类的基础概念:从零开始学面向对象】
开发语言·php