Android 项目常见问题与 23 种设计模式应用对照表(含 Kotlin 示例)

共 120 个 Android 相关问题、120 段示例代码:GoF 23 种设计模式各 5 问,另附 5 个综合场景。

这份文档用于训练"从问题选择方案",不是"拿着模式找代码"。表中的模式都是候选方案,不是唯一答案。很多问题用提取函数、依赖注入、Kotlin 函数类型、密封类、Flow 或现有框架就能更好地解决。

使用说明

  1. 先描述代码坏味道:分支增长、修改范围大、第三方依赖泄漏、难测试、状态混乱等。
  2. 再写清楚变化点:什么会增加、替换、组合或独立变化?这个变化是否真实存在?
  3. 先给出"不使用设计模式"的最简单方案,再比较候选模式。
  4. 引入模式后模拟一次新需求,检查修改文件数、测试难度和理解成本。
  5. 如果没有明确收益,就保留简单方案。

**代码约定:**示例使用 Kotlin、AndroidX、Hilt、协程、Flow 等常见技术,重点展示职责划分;省略 import、权限声明、完整错误处理和框架配置,不能直接视为完整可运行项目。部分示例专门展示更简单的替代方案,用来避免过度设计。

**频率提醒:**单例、工厂、适配器、外观、装饰器、代理、观察者、策略、状态等在 Android 中较容易遇到;原型、桥接、享元、解释器、访问者等相对少见。少见模式用于理解决策,不建议为了覆盖率强行引入。


一、创建型模式

1. 单例模式(Singleton)

编号 项目中的问题 可以考虑的模式 不要机械套用
1 多个模块各自创建 OkHttpClient,连接池、线程池和拦截器配置无法复用,资源消耗偏高。 单例模式 优先让依赖注入框架管理单例生命周期;不要在 Application 或 companion object 中堆全局可变对象。
2 埋点 SDK 在 Application、Activity 和 ViewModel 中被重复初始化,偶尔出现重复注册或初始化顺序问题。 单例模式、外观模式 单例只解决实例数量,不自动解决线程安全、初始化时机和隐私授权;未授权前不能提前初始化统计 SDK。
3 多个页面需要共享同一个内存缓存,但分别创建缓存实例后容量上限失效,数据也无法统一清理。 单例模式 缓存是否需要全局共享应先确认;用户级数据要能在退出登录时清理,测试时也要能替换实例。
4 音乐播放控制器被多个页面分别创建,导致播放器状态、音频焦点和通知栏状态互不一致。 单例模式、外观模式 播放生命周期通常更适合由 Service 或专门的状态拥有者管理,不能只靠一个全局对象解决后台播放问题。
5 蓝牙连接管理器在多个界面重复创建,扫描、连接和断连操作互相干扰。 单例模式、中介者模式 要考虑进程生命周期、蓝牙权限和页面销毁;不要为了单例而让它永久持有 Activity、Context 或回调。
示例 1:由 Hilt 管理唯一的 OkHttpClient
kotlin 复制代码
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
    @Provides
    @Singleton
    fun provideOkHttpClient(): OkHttpClient =
        OkHttpClient.Builder().retryOnConnectionFailure(true).build()
}
示例 2:统计 SDK 只在授权后初始化一次
kotlin 复制代码
@Singleton
class AnalyticsInitializer @Inject constructor(
    @ApplicationContext private val context: Context,
    private val consentStore: ConsentStore
) {
    private var started = false

    @Synchronized
    fun startIfAllowed() {
        if (started || !consentStore.hasConsent()) return
        ThirdPartyAnalytics.init(context)
        started = true
    }
}
示例 3:共享缓存并提供明确的清理入口
kotlin 复制代码
@Singleton
class UserProfileCache @Inject constructor() {
    private val cache = LruCache<String, UserProfile>(100)

    fun put(profile: UserProfile) = cache.put(profile.id, profile)
    fun get(userId: String): UserProfile? = cache.get(userId)
    fun clearOnLogout() = cache.evictAll()
}
示例 4:播放状态只有一个拥有者
kotlin 复制代码
@Singleton
class PlaybackController @Inject constructor(private val player: Player) {
    val state = MutableStateFlow<PlaybackState>(PlaybackState.Idle)

    fun play(uri: Uri) {
        player.setMediaItem(MediaItem.fromUri(uri))
        player.prepare()
        player.play()
    }
}
// Service 持有播放器并处理后台生命周期,页面只依赖 PlaybackController。
示例 5:蓝牙管理器只持有应用 Context
kotlin 复制代码
@Singleton
class BleConnectionManager @Inject constructor(
    @ApplicationContext private val context: Context
) {
    private val bluetoothManager =
        context.getSystemService(BluetoothManager::class.java)

    fun connect(address: String) { /* 权限检查后统一执行连接 */ }
    fun disconnect() { /* 关闭 GATT、清理回调和连接状态 */ }
}

2. 建造者模式(Builder)

编号 项目中的问题 可以考虑的模式 不要机械套用
6 下载任务包含 URL、保存路径、超时、重试、通知栏、是否仅 Wi-Fi 等大量可选参数,构造函数调用越来越难读。 建造者模式 Kotlin 的 data class、默认参数和命名参数通常更简洁;只有构建过程确有多步骤约束时才需要 Builder。
7 通用弹窗支持标题、内容、多个按钮、输入框、倒计时和样式配置,不同页面需要不同组合。 建造者模式 不要为两三个参数设计链式 Builder;配置项之间存在依赖或校验顺序时,Builder 才更有价值。
8 通知创建需要渠道、小图标、大图标、进度、动作按钮和兼容不同系统版本,构建步骤较复杂。 建造者模式 NotificationCompat.Builder 已提供构建能力,通常直接使用或做薄封装,不要再造一套等价的 Builder。
9 图片请求需要尺寸、缩放方式、占位图、缓存策略、变换器和失效监听,调用方经常漏配必要参数。 建造者模式 如果 Glide、Coil 等库的请求 API 已足够清晰,应优先复用;封装必须带来统一约束或隔离 SDK 的收益。
10 自定义报表任务需要先设置数据源,再配置筛选、排序和输出格式,最后统一校验后生成任务对象。 建造者模式 Builder 不应变成可无限修改的万能配置容器;构建后对象最好保持不可变,并明确哪些字段是必需的。
示例 6:优先用命名参数和默认参数构建下载配置
kotlin 复制代码
data class DownloadConfig(
    val url: String,
    val timeoutSeconds: Long = 30,
    val retryCount: Int = 2,
    val wifiOnly: Boolean = true,
    val showNotification: Boolean = true
)

val config = DownloadConfig(url = fileUrl, retryCount = 3, wifiOnly = false)
// 只有构建步骤和跨字段校验继续变复杂时,再引入专用 Builder。
示例 7:用 Builder 校验弹窗配置
kotlin 复制代码
class DialogConfig private constructor(val title: String, val inputHint: String?) {
    class Builder(private val title: String) {
        private var inputHint: String? = null
        fun input(hint: String) = apply { inputHint = hint }
        fun build(): DialogConfig {
            require(title.isNotBlank()) { "标题不能为空" }
            return DialogConfig(title, inputHint)
        }
    }
}

val config = DialogConfig.Builder("修改昵称").input("请输入昵称").build()
示例 8:直接复用 NotificationCompat.Builder
kotlin 复制代码
fun buildDownloadNotification(context: Context, progress: Int): Notification =
    NotificationCompat.Builder(context, ChannelIds.DOWNLOAD)
        .setSmallIcon(R.drawable.ic_download)
        .setContentTitle("正在下载")
        .setProgress(100, progress, false)
        .setOnlyAlertOnce(true)
        .build()
示例 9:复用 Coil 的 ImageRequest.Builder
kotlin 复制代码
val request = ImageRequest.Builder(context)
    .data(imageUrl)
    .size(480, 480)
    .placeholder(R.drawable.image_placeholder)
    .error(R.drawable.image_error)
    .transformations(CircleCropTransformation())
    .build()

imageLoader.enqueue(request)
示例 10:构建不可变报表任务并集中校验
kotlin 复制代码
class ReportTask private constructor(val source: DataSource, val format: OutputFormat) {
    class Builder {
        private var source: DataSource? = null
        private var format: OutputFormat? = null
        fun source(value: DataSource) = apply { source = value }
        fun format(value: OutputFormat) = apply { format = value }
        fun build() = ReportTask(
            checkNotNull(source) { "缺少数据源" },
            checkNotNull(format) { "缺少输出格式" }
        )
    }
}

3. 工厂方法模式(Factory Method)

编号 项目中的问题 可以考虑的模式 不要机械套用
11 不同类型的 Worker 需要不同依赖,默认 WorkerFactory 无法按项目要求完成构造。 工厂方法模式 WorkManager 已定义创建扩展点,按框架实现即可;不要在 Worker 内部再用 Service Locator 随意取依赖。
12 ViewModel 需要 Repository、SavedStateHandle 等构造参数,系统默认创建方式无法满足。 工厂方法模式 优先使用 Hilt 等依赖注入或框架提供的 Factory;只有一两个简单参数时,不必再叠加多层工厂。
13 ViewPager2 的每个页面需要创建不同类型 Fragment,页面类型与 Fragment 构造逻辑开始散落。 工厂方法模式 页面少且稳定时,一个清晰的 when 就够了;Fragment 参数仍应通过 arguments 等框架机制传递。
14 列表包含文本、图片、视频等多种 Item,创建 ViewHolder 的逻辑不断膨胀。 工厂方法模式 onCreateViewHolder 本身已有创建职责;类型不多时直接分支更直观,复杂时可采用 Adapter Delegates。
15 下载完成、消息提醒、通话等通知需要按类型创建,但各类型又有不同的动作和兼容逻辑。 工厂方法模式 不要只把一段 when 原样搬进工厂就宣称解耦;工厂应让创建变化集中,并保持调用方依赖稳定抽象。
示例 11:按 Worker 类型创建实例并注入依赖
kotlin 复制代码
class AppWorkerFactory(private val repository: TaskRepository) : WorkerFactory() {
    override fun createWorker(
        context: Context, className: String, params: WorkerParameters
    ): ListenableWorker? = when (className) {
        SyncWorker::class.qualifiedName -> SyncWorker(context, params, repository)
        else -> null // 交给其他 Factory 或默认 Factory
    }
}
示例 12:通过 ViewModelProvider.Factory 传入构造参数
kotlin 复制代码
class DetailViewModelFactory(
    private val repository: NewsRepository,
    private val newsId: String
) : ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        require(modelClass.isAssignableFrom(DetailViewModel::class.java))
        @Suppress("UNCHECKED_CAST")
        return DetailViewModel(repository, newsId) as T
    }
}
示例 13:集中创建 Tab 对应的 Fragment
kotlin 复制代码
enum class TabType { NEWS, VIDEO, PROFILE }

object TabFragmentFactory {
    fun create(type: TabType): Fragment = when (type) {
        TabType.NEWS -> NewsFragment()
        TabType.VIDEO -> VideoFragment()
        TabType.PROFILE -> ProfileFragment()
    }
}
示例 14:Adapter 将 ViewHolder 创建变化集中起来
kotlin 复制代码
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
    val inflater = LayoutInflater.from(parent.context)
    return when (viewType) {
        ItemType.TEXT -> TextViewHolder(inflater.inflate(R.layout.item_text, parent, false))
        ItemType.IMAGE -> ImageViewHolder(inflater.inflate(R.layout.item_image, parent, false))
        else -> error("未知类型:$viewType")
    }
}
示例 15:用模板创建流程封装通知的创建变化
kotlin 复制代码
abstract class NotificationCreator {
    protected abstract fun create(context: Context, data: NotificationData): Notification

    fun show(context: Context, data: NotificationData) {
        NotificationManagerCompat.from(context).notify(data.id, create(context, data))
    }
}

class DownloadNotificationCreator : NotificationCreator() {
    override fun create(context: Context, data: NotificationData): Notification =
        NotificationCompat.Builder(context, ChannelIds.DOWNLOAD).setContentTitle(data.title).build()
}

4. 抽象工厂模式(Abstract Factory)

编号 项目中的问题 可以考虑的模式 不要机械套用
16 国内版和海外版分别使用一整套推送、统计、登录实现,要求同一版本内各组件配套,不能混用。 抽象工厂模式 如果各组件可独立替换,分别注入策略或适配器更灵活;Build Variant 加依赖注入通常比手工工厂简单。
17 测试环境与生产环境需要成组切换网络数据源、日志输出和本地存储实现,避免误连真实服务。 抽象工厂模式 不要用工厂在运行时到处判断环境;环境配置应在依赖图组装时确定,并防止测试实现进入生产包。
18 不同硬件设备需要配套创建扫码器、打印机和读卡器驱动,同一设备系列之间才兼容。 抽象工厂模式、适配器模式 只有单一设备或单一组件变化时,不需要"产品族"抽象;先确认配套约束是否真实存在。
19 应用支持多套完整 UI 组件风格,同套主题中的按钮、弹窗、输入框和配色必须一致。 抽象工厂模式 Android 主题、样式、设计系统和资源限定符通常更合适;不要用对象工厂替代成熟的资源机制。
20 视频能力包含播放器、缓存器和渲染器,不同内核之间只能按固定组合使用。 抽象工厂模式、桥接模式 组合数量少且长期固定时直接装配即可;抽象工厂增加接口较多,必须能证明它减少了错误组合。
示例 16:为不同地区创建相互配套的服务族
kotlin 复制代码
interface RegionServiceFactory {
    fun push(): PushService
    fun analytics(): AnalyticsService
    fun login(): LoginService
}

class DomesticServiceFactory : RegionServiceFactory {
    override fun push(): PushService = DomesticPushAdapter()
    override fun analytics(): AnalyticsService = DomesticAnalyticsAdapter()
    override fun login(): LoginService = DomesticLoginAdapter()
}
示例 17:测试环境成组提供 Fake 实现
kotlin 复制代码
interface EnvironmentFactory {
    fun remote(): NewsRemoteDataSource
    fun logger(): AppLogger
    fun storage(): LocalStorage
}

class FakeEnvironmentFactory : EnvironmentFactory {
    override fun remote() = FakeNewsRemoteDataSource()
    override fun logger(): AppLogger = NoOpLogger
    override fun storage(): LocalStorage = InMemoryLocalStorage()
}
示例 18:为硬件系列创建兼容的外设组合
kotlin 复制代码
interface DeviceKitFactory {
    fun scanner(): ScannerDriver
    fun printer(): PrinterDriver
    fun cardReader(): CardReaderDriver
}

class VendorADeviceKitFactory(private val config: VendorAConfig) : DeviceKitFactory {
    override fun scanner() = VendorAScanner(config)
    override fun printer() = VendorAPrinter(config)
    override fun cardReader() = VendorACardReader(config)
}
示例 19:组件族工厂示意,以及更推荐的主题方式
kotlin 复制代码
interface UiKitFactory {
    fun buttonStyle(): ButtonStyle
    fun dialogStyle(): DialogStyle
}

// 实际 Android 项目通常直接切换主题,而不是创建一套 UIKitFactory:
@Composable
fun AppTheme(content: @Composable () -> Unit) {
    MaterialTheme(colorScheme = AppLightColors, typography = AppTypography, content = content)
}
示例 20:保证播放器、缓存和渲染器属于同一内核系列
kotlin 复制代码
interface VideoKitFactory {
    fun player(): VideoPlayer
    fun cache(): VideoCache
    fun renderer(): VideoRenderer
}

class ExoVideoKitFactory(private val context: Context) : VideoKitFactory {
    override fun player(): VideoPlayer = ExoVideoPlayer(context)
    override fun cache(): VideoCache = ExoVideoCache(context)
    override fun renderer(): VideoRenderer = ExoVideoRenderer()
}

5. 原型模式(Prototype)

编号 项目中的问题 可以考虑的模式 不要机械套用
21 多个网络请求都以同一配置为模板,只修改少量超时、请求头或缓存参数。 原型模式 Kotlin copy() 已覆盖多数场景;注意它默认是浅拷贝,不要把共享可变集合当成独立副本。
22 画板需要以已有笔迹为模板创建新笔迹,之后独立修改颜色和点位,不能影响原笔迹。 原型模式 不可变对象可以直接共享;包含 Path、数组或可变列表时,要明确复制深度。
23 运营通知由已有草稿复制生成,只改标题、跳转链接和展示时间。 原型模式 简单数据类直接 copy() 即可,不要额外定义 Cloneable 和公共 clone() 体系。
24 图片编辑方案包含滤镜、裁剪和调色步骤,需要复制整套方案后单独调整一步。 原型模式 如果步骤集合不可变,复制外层对象就足够;若步骤自身可变,则必须逐级复制。
25 文档编辑器打开已有文档时要创建可编辑草稿,取消修改后原文档不能发生变化。 原型模式、备忘录模式 深拷贝可能成本很高;大文件可优先使用不可变数据、写时复制或差量修改。
示例 21:从请求模板复制配置
kotlin 复制代码
data class RequestConfig(
    val timeoutSeconds: Long,
    val headers: Map<String, String>,
    val cacheEnabled: Boolean
)

val base = RequestConfig(30, mapOf("App-Version" to "1.0"), true)
val upload = base.copy(
    timeoutSeconds = 120,
    headers = base.headers + ("Content-Type" to "application/octet-stream")
)
示例 22:复制笔迹时复制可变点位集合
kotlin 复制代码
data class Stroke(val color: Int, val points: List<Offset>) {
    fun duplicate(): Stroke = copy(points = points.toList())
}

val draft = originalStroke.duplicate().copy(color = Color.Blue.toArgb())
// 如果 points 中的元素自身可变,还需要继续复制元素。
示例 23:复制通知草稿
kotlin 复制代码
data class NotificationDraft(
    val title: String,
    val deepLink: String,
    val displayAt: Long
)

val campaignDraft = savedDraft.copy(
    title = "限时优惠",
    displayAt = System.currentTimeMillis() + 3600_000
)
示例 24:复制图片编辑步骤列表
kotlin 复制代码
data class EditRecipe(val steps: List<EditStep>) {
    fun duplicate(): EditRecipe = copy(steps = steps.map { it.copyStep() })
}

val blackWhiteRecipe = currentRecipe.duplicate().also {
    it.steps.filterIsInstance<ColorAdjustStep>().forEach { step -> step.saturation = 0f }
}
示例 25:为文档创建独立编辑草稿
kotlin 复制代码
class DocumentDraft(val paragraphs: MutableList<Paragraph>) {
    fun deepCopy(): DocumentDraft = DocumentDraft(
        paragraphs.map { paragraph ->
        paragraph.copy(runs = paragraph.runs.map { run -> run.copy() }.toMutableList())
    }.toMutableList()
    )
}

val editingDraft = openedDocument.draft.deepCopy()

6. 适配器模式(Adapter)

编号 项目中的问题 可以考虑的模式 不要机械套用
26 Firebase 等统计 SDK 的事件名、参数类型和调用方式不适合业务,且 SDK 类型散落在 ViewModel 中。 适配器模式 只有一次简单调用时可直接使用 SDK;封装应服务于统一语义、测试或替换需求。
27 第三方登录 SDK 返回自己的 User、Token 和异常模型,业务层被迫依赖这些类型。 适配器模式 适配器要完成模型和异常语义转换,不只是把 SDK 方法换个名字继续转发。
28 不同推送厂商的 Token 获取、消息解析和点击处理接口不一致。 适配器模式 统一接口要保留厂商特有能力的扩展出口,不能为求一致而丢失关键功能。
29 定位 SDK 的坐标系、精度和错误码与业务模型不同,多个页面各自转换。 适配器模式、外观模式 坐标转换和权限异常要集中处理;不要在适配器中持有页面或自行弹权限弹窗。
30 业务代码直接使用播放器内核 API,替换内核时需要修改所有播放页面。 适配器模式、外观模式 只使用一个简单播放方法时无需包装;需要稳定状态模型和可测试性时再抽业务接口。
示例 26:把统计 SDK 适配为业务接口
kotlin 复制代码
interface AnalyticsTracker { fun track(event: AppEvent) }

class FirebaseTrackerAdapter(
    private val firebase: FirebaseAnalytics
) : AnalyticsTracker {
    override fun track(event: AppEvent) {
        val params = Bundle().apply { event.params.forEach { (k, v) -> putString(k, v) } }
        firebase.logEvent(event.name, params)
    }
}
示例 27:隔离第三方登录模型
kotlin 复制代码
interface LoginProvider { suspend fun login(): Result<AppAccount> }

class OAuthLoginAdapter(private val sdk: OAuthSdk) : LoginProvider {
    override suspend fun login(): Result<AppAccount> = runCatching {
        val result = sdk.login()
        AppAccount(id = result.userId, token = result.accessToken)
    }
}
示例 28:统一推送 Token 接口
kotlin 复制代码
interface PushProvider { suspend fun getToken(): String }

class VendorPushAdapter(private val pushApi: VendorPushApi) : PushProvider {
    override suspend fun getToken(): String =
        pushApi.awaitRegistrationId() ?: error("推送 Token 为空")
}
示例 29:把定位结果转换成业务位置模型
kotlin 复制代码
data class AppLocation(val latitude: Double, val longitude: Double, val accuracy: Float)

class LocationAdapter(private val client: FusedLocationProviderClient) {
    suspend fun current(): AppLocation = client.awaitCurrentLocation().let {
        AppLocation(it.latitude, it.longitude, it.accuracy)
    }
}
示例 30:用稳定播放器接口隔离 ExoPlayer
kotlin 复制代码
interface AudioPlayer {
    fun play(uri: Uri)
    fun pause()
    fun release()
}

class ExoAudioPlayerAdapter(private val player: ExoPlayer) : AudioPlayer {
    override fun play(uri: Uri) {
        player.setMediaItem(MediaItem.fromUri(uri)); player.prepare(); player.play()
    }
    override fun pause() = player.pause()
    override fun release() = player.release()
}

二、结构型模式

7. 桥接模式(Bridge)

编号 项目中的问题 可以考虑的模式 不要机械套用
31 音乐、短视频等播放控制方式会独立演进,ExoPlayer 等播放内核也会独立替换,继承组合开始膨胀。 桥接模式 只有"控制抽象"和"内核实现"两个维度都真实变化时才使用;单一变化用策略或适配器即可。
32 头像、横幅等图像处理流程不同,Canvas 与 OpenGL 等渲染后端也需要独立替换。 桥接模式 不要为了想象中的多后端提前拆两套继承体系;Android 图片库现有能力可能已经足够。
33 报表、订单等业务导出结构不同,同时需要 PDF、图片等不同输出后端。 桥接模式 如果只有一种文档和一种格式,一个导出函数更简单;不要把普通参数分支都升级成桥接。
34 单次、连续等扫码交互会变化,MLKit、ZXing 等识别引擎也可能替换。 桥接模式、适配器模式 引擎替换本身用适配器就能解决;只有扫描交互也需要独立扩展时才增加桥接层。
35 消息、下载等通知内容逻辑不同,手机通知栏、穿戴设备等投递方式也不同。 桥接模式 多端投递需求必须真实存在;普通通知直接使用 NotificationCompat,不要抽象出虚假的平台维度。
示例 31:播放控制与播放内核独立变化
kotlin 复制代码
interface PlayerEngine { fun play(uri: Uri); fun pause() }

abstract class PlayerController(protected val engine: PlayerEngine) {
    abstract fun start(content: Content)
}

class MusicController(engine: PlayerEngine) : PlayerController(engine) {
    override fun start(content: Content) = engine.play(content.audioUri)
}
class ExoPlayerEngine(private val player: ExoPlayer) : PlayerEngine {
    override fun play(uri: Uri) { /* 设置 MediaItem 并播放 */ }
    override fun pause() = player.pause()
}
示例 32:图像处理抽象与渲染后端解耦
kotlin 复制代码
interface RenderBackend { fun blur(bitmap: Bitmap, radius: Float): Bitmap }

abstract class ImageEffect(protected val backend: RenderBackend) {
    abstract fun apply(source: Bitmap): Bitmap
}

class AvatarEffect(backend: RenderBackend) : ImageEffect(backend) {
    override fun apply(source: Bitmap): Bitmap = backend.blur(source.cropSquare(), 8f)
}
示例 33:文档业务与输出格式分别扩展
kotlin 复制代码
interface DocumentWriter { fun write(document: ExportDocument): Uri }

abstract class Exporter(protected val writer: DocumentWriter) {
    abstract fun export(data: ExportData): Uri
}

class OrderExporter(writer: DocumentWriter) : Exporter(writer) {
    override fun export(data: ExportData): Uri = writer.write(data.toOrderDocument())
}
示例 34:扫码会话与识别引擎分离
kotlin 复制代码
interface ScanEngine { suspend fun recognize(frame: ImageProxy): List<Barcode> }

abstract class ScanSession(protected val engine: ScanEngine) {
    abstract suspend fun onFrame(frame: ImageProxy): ScanResult
}

class SingleScanSession(engine: ScanEngine) : ScanSession(engine) {
    override suspend fun onFrame(frame: ImageProxy): ScanResult =
        engine.recognize(frame).firstOrNull()?.let(::Success) ?: KeepScanning
}
示例 35:通知内容与投递渠道解耦
kotlin 复制代码
interface NotificationSink { fun deliver(payload: NotificationPayload) }

abstract class AppNotification(private val sink: NotificationSink) {
    abstract fun send()
}

class DownloadNotification(sink: NotificationSink, private val progress: Int) : AppNotification(sink) {
    override fun send() = sink.deliver(NotificationPayload("下载进度", "$progress%"))
}

8. 组合模式(Composite)

编号 项目中的问题 可以考虑的模式 不要机械套用
36 一次业务事件需要同时上报多个统计平台,调用方不断出现平台列表和重复循环。 组合模式 只有平台选择逻辑时可用策略;组合适合"多个实现被当成一个整体使用",不是简单存一个 List。
37 App 启动时需要把一组初始化任务作为一个步骤执行,还可能按业务继续嵌套任务组。 组合模式 有依赖关系、并发要求或启动顺序约束时,应使用任务图或启动框架,而不是简单顺序循环。
38 动态表单中既有单个字段,也有可嵌套字段分组,校验和收集值时希望统一处理。 组合模式、迭代器模式 固定且只有一层的表单不需要树结构;组合对象应避免让父节点和子节点接口语义混乱。
39 播放列表既包含单曲,也包含子歌单,页面和播放器希望用同一方式计算时长、展开和播放。 组合模式 播放策略、随机播放等不一定属于组合节点职责,不要形成难以维护的巨型接口。
40 日志需要同时写入 Logcat、文件和远程平台,业务代码希望只调用一个 Logger。 组合模式 远程日志要防止递归上报和阻塞主线程;开发环境只有 Logcat 时不需要组合对象。
示例 36:把多个统计器组合成一个统计器
kotlin 复制代码
class CompositeTracker(
    private val trackers: List<AnalyticsTracker>
) : AnalyticsTracker {
    override fun track(event: AppEvent) {
        trackers.forEach { tracker -> runCatching { tracker.track(event) } }
    }
}

val tracker: AnalyticsTracker = CompositeTracker(listOf(firebaseTracker, companyTracker))
示例 37:把初始化任务组当成一个任务
kotlin 复制代码
interface StartupTask { suspend fun start() }

class TaskGroup(private val tasks: List<StartupTask>) : StartupTask {
    override suspend fun start() {
        tasks.forEach { it.start() } // 有依赖或并发需求时改用任务调度器
    }
}
示例 38:统一校验字段与嵌套表单分组
kotlin 复制代码
interface FormComponent { fun validate(): List<FormError> }

class FieldComponent(private val field: FormField) : FormComponent {
    override fun validate() = field.rules.mapNotNull { it.check(field.value) }
}

class SectionComponent(private val children: List<FormComponent>) : FormComponent {
    override fun validate() = children.flatMap { it.validate() }
}
示例 39:统一处理单曲和子歌单
kotlin 复制代码
sealed interface PlayNode { fun durationMs(): Long }

data class Song(val duration: Long) : PlayNode {
    override fun durationMs() = duration
}

data class SongGroup(val children: List<PlayNode>) : PlayNode {
    override fun durationMs() = children.sumOf { it.durationMs() }
}
示例 40:组合多个日志输出端
kotlin 复制代码
interface AppLogger { fun log(level: LogLevel, message: String) }

class CompositeLogger(private val sinks: List<AppLogger>) : AppLogger {
    override fun log(level: LogLevel, message: String) {
        sinks.forEach { it.log(level, message) }
    }
}

9. 装饰器模式(Decorator)

编号 项目中的问题 可以考虑的模式 不要机械套用
41 希望给现有网络数据源增加日志,又不修改 Retrofit 数据源或业务调用方。 装饰器模式、代理模式 只有一处简单日志时直接写在该实现中更清楚;装饰器适合保持同一接口并组合附加职责。
42 多个数据源都需要统一的重试和退避能力,但不希望把重试逻辑复制到各实现。 装饰器模式、策略模式 网络库已有重试能力时先复用;重试必须考虑幂等性、取消和超时,不能无脑重复请求。
43 希望在 RemoteDataSource 外透明增加内存缓存,页面仍依赖原来的数据接口。 装饰器模式 缓存一致性和失效策略比包装结构更重要;复杂离线同步应放在 Repository,而不是堆装饰层。
44 文件流需要按需叠加缓冲、压缩或加密,同时保持 InputStream 的使用方式。 装饰器模式 优先组合 JDK/Android 已有流实现;注意关闭顺序,避免重复关闭或资源泄漏。
45 多个按钮需要增加防重复点击或点击埋点,但不想修改原点击业务逻辑。 装饰器模式 Compose 可用简单函数包装或 Modifier;不要因为一个按钮就建立庞大的 Listener 装饰类体系。
示例 41:为数据源增加日志装饰
kotlin 复制代码
interface NewsDataSource { suspend fun load(): List<News> }

class LoggingNewsDataSource(
    private val delegate: NewsDataSource,
    private val logger: AppLogger
) : NewsDataSource {
    override suspend fun load(): List<News> =
        delegate.load().also { logger.log(LogLevel.DEBUG, "返回 ${it.size} 条") }
}
示例 42:在接口外组合重试能力
kotlin 复制代码
class RetryNewsDataSource(
    private val delegate: NewsDataSource,
    private val backoff: BackoffStrategy
) : NewsDataSource {
    override suspend fun load(): List<News> {
        var lastFailure: IOException? = null
        repeat(3) { attempt ->
            try {
                return delegate.load()
            } catch (error: IOException) {
                lastFailure = error
                if (attempt < 2) delay(backoff.delayFor(attempt))
            }
        }
        throw checkNotNull(lastFailure)
    }
}
示例 43:透明增加缓存层
kotlin 复制代码
class CachedNewsDataSource(
    private val delegate: NewsDataSource,
    private val cache: NewsMemoryCache
) : NewsDataSource {
    override suspend fun load(): List<News> =
        cache.getValid() ?: delegate.load().also(cache::put)
}
示例 44:按需组合文件流能力
kotlin 复制代码
fun openDecryptedStream(file: File, cipher: Cipher): InputStream =
    BufferedInputStream(
        CipherInputStream(FileInputStream(file), cipher)
    )

openDecryptedStream(file, cipher).use { input ->
    val content = input.readBytes()
}
示例 45:装饰 View 的点击监听
kotlin 复制代码
class DebouncedClickListener(
    private val intervalMs: Long = 500,
    private val delegate: View.OnClickListener
) : View.OnClickListener {
    private var lastClickAt = 0L
    override fun onClick(view: View) {
        val now = SystemClock.elapsedRealtime()
        if (now - lastClickAt < intervalMs) return
        lastClickAt = now
        delegate.onClick(view)
    }
}

10. 外观模式(Facade)

编号 项目中的问题 可以考虑的模式 不要机械套用
46 拍照流程涉及权限、相机绑定、生命周期、图片保存和旋转处理,页面代码充斥大量细节。 外观模式 Facade 只简化入口,不应把 Activity 生命周期永远藏住;权限交互仍需和页面生命周期正确衔接。
47 分享文件需要生成 Uri、配置 FileProvider、授予权限并创建 Chooser,多个页面重复实现。 外观模式 简单文本分享直接创建 Intent 即可;文件分享封装要处理 Uri 权限和异常,而不是吞掉错误。
48 下载中心同时操作任务队列、网络、存储、通知栏和前台服务,业务入口非常复杂。 外观模式、命令模式 Facade 不应成为无所不知的 God Object;子系统仍要各自负责自己的状态和测试。
49 联系人选择涉及 Activity Result、权限、ContentResolver 查询和联系人模型转换。 外观模式、适配器模式 Activity Result 必须在有效生命周期位置注册,不能随意放进普通单例中延迟初始化。
50 支付流程包括下单、调起 SDK、处理 Activity 结果和服务端验签,调用方只需一个业务入口。 外观模式 支付结果不能只信任客户端回调;Facade 不能让调用方误以为 SDK 返回成功就等于支付成功。
示例 46:给页面提供简单的拍照入口
kotlin 复制代码
class CameraCaptureFacade(private val camera: CameraController) {
    suspend fun capture(): Result<Uri> = runCatching {
        camera.awaitReady()
        val file = camera.createOutputFile()
        camera.takePicture(file)
        file.toUri()
    }
}
// 页面负责触发权限请求并启动流程,相机细节留在 Facade 后面。
示例 47:统一处理文件分享步骤
kotlin 复制代码
class ShareFacade(private val context: Context) {
    fun share(file: File, mimeType: String) {
        val uri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)
        val intent = Intent(Intent.ACTION_SEND).apply {
            type = mimeType
            putExtra(Intent.EXTRA_STREAM, uri)
            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        }
        context.startActivity(Intent.createChooser(intent, "分享到"))
    }
}
示例 48:用 DownloadCenter 隐藏下载子系统
kotlin 复制代码
class DownloadCenter(
    private val queue: DownloadQueue,
    private val storage: DownloadStorage,
    private val notifier: DownloadNotifier
) {
    suspend fun enqueue(request: DownloadRequest): DownloadId {
        val target = storage.allocate(request.fileName)
        return queue.enqueue(request, target).also { notifier.showEnqueued(it) }
    }
}
示例 49:对页面隐藏联系人查询细节
kotlin 复制代码
class ContactFacade(private val resolver: ContentResolver) {
    fun readContact(uri: Uri): AppContact? =
        resolver.query(uri, null, null, null, null)?.use { cursor ->
            if (cursor.moveToFirst()) cursor.toAppContact() else null
        }
}
// 页面仍通过 Activity Result API 获取 uri,并负责必要权限。
示例 50:支付入口统一编排,最终结果由服务端确认
kotlin 复制代码
class PaymentFacade(
    private val orderApi: OrderApi,
    private val sdk: PaymentSdk,
    private val verifyApi: PaymentVerifyApi
) {
    suspend fun pay(cart: Cart): PaymentResult {
        val order = orderApi.create(cart)
        sdk.launch(order.sdkParams) // 客户端回调仅用于流程衔接
        return verifyApi.verify(order.id)
    }
}

11. 享元模式(Flyweight)

编号 项目中的问题 可以考虑的模式 不要机械套用
51 地图上数万个 Marker 使用少量相同样式,却反复解码相同图标,内存和 CPU 开销明显增加。 享元模式 先用性能分析确认图标重复创建是瓶颈;共享对象必须不可变,Marker 的位置等信息仍属于外部状态。
52 聊天列表包含大量 Emoji,相同样式的字体、颜色等描述对象被重复创建。 享元模式 Android 资源和字体系统可能已有缓存;不要为了少量 Emoji 自建全局缓存,也不能共享可变 Span 状态。
53 自定义网格或表格一次绘制大量单元格,但相同类型单元格使用完全一致的 Paint 配置。 享元模式 复用少量 Paint 往往只是普通对象复用;多线程或绘制过程中随意修改共享 Paint 会引入问题。
54 大量列表项使用相同 Drawable 资源,希望复用底层资源而保留各自的 Drawable 实例状态。 享元模式 Android Resources 已做不少缓存;需要单独 tint、alpha 或 bounds 时仍要注意 Drawable 状态隔离。
55 粒子、弹幕等对象数量很大,但字体、颜色、纹理等样式只有少数几种。 享元模式、对象池 享元共享的是内在状态,不等于复用整个可变对象;先减少分配和绘制次数,再决定是否需要缓存。
示例 51:按样式共享地图 Marker 图标
kotlin 复制代码
class MarkerIconFactory {
    private val icons = mutableMapOf<MarkerStyle, BitmapDescriptor>()

    fun get(style: MarkerStyle): BitmapDescriptor = icons.getOrPut(style) {
        BitmapDescriptorFactory.fromBitmap(renderIcon(style))
    }
}
// MarkerStyle 必须是不可变且正确实现 equals/hashCode 的数据类型。
示例 52:共享不可变 Emoji 样式
kotlin 复制代码
data class EmojiStyle(val typeface: Typeface, val color: Int, val sizePx: Float)

class EmojiStyleFactory {
    private val styles = mutableMapOf<String, EmojiStyle>()
    fun get(key: String, create: () -> EmojiStyle): EmojiStyle = styles.getOrPut(key, create)
}

class EmojiSpan(val style: EmojiStyle, val code: String)
示例 53:按单元格类型复用 Paint 配置
kotlin 复制代码
class CellPaints {
    private val paints = EnumMap<CellType, Paint>(CellType::class.java)
    fun get(type: CellType): Paint = paints.getOrPut(type) { createPaint(type) }
}

fun drawCell(canvas: Canvas, cell: Cell, paints: CellPaints) {
    canvas.drawRect(cell.bounds, paints.get(cell.type)) // bounds 是外部状态
}
示例 54:复用 Drawable.ConstantState 中的共享资源
kotlin 复制代码
class DrawableStateFactory(private val resources: Resources) {
    private var state: Drawable.ConstantState? = null

    fun create(): Drawable {
        val current = state ?: ResourcesCompat.getDrawable(resources, R.drawable.ic_badge, null)
            ?.constantState.also { state = it }
        return checkNotNull(current).newDrawable(resources)
    }
}
示例 55:粒子位置独立,样式共享
kotlin 复制代码
data class ParticleStyle(val color: Int, val radius: Float, val texture: Bitmap)
data class Particle(var x: Float, var y: Float, val style: ParticleStyle)

val sharedStyle = ParticleStyle(Color.WHITE, 4f, dotBitmap)
val particles = List(10_000) { Particle(it.toFloat(), 0f, sharedStyle) }

12. 代理模式(Proxy)

编号 项目中的问题 可以考虑的模式 不要机械套用
56 希望用接口声明 HTTP API,由框架在运行时生成网络调用实现。 动态代理模式 Retrofit 已完成动态代理,业务代码直接使用即可;不要为普通 Repository 再手写无意义代理。
57 图片解码器、识别模型等重型对象初始化很慢,希望首次使用时再创建。 虚拟代理、延迟初始化 Kotlin by lazy 通常足够;注意初始化线程、失败重试和生命周期,不要默认延迟就一定更快。
58 定位服务在调用前必须检查权限,未授权时不能进入真正的定位实现。 保护代理 代理不能代替系统权限流程;权限结果可能随时变化,实际调用前仍需检查并处理安全异常。
59 跨进程服务可能在本进程或另一进程,调用方希望使用同一接口而不关心 Binder 细节。 远程代理 AIDL 已生成本地实现与代理选择逻辑;要处理 Binder 死亡、线程和跨进程异常。
60 数据访问实现不能直接在主线程执行,希望代理统一切换 IO 线程,调用方仍依赖原接口。 代理模式 优先在 Repository 或用例层明确协程调度;DAO 本身应使用 suspend,不要隐藏不必要的线程切换。
示例 56:Retrofit 根据接口创建动态代理
kotlin 复制代码
interface UserApi {
    @GET("users/{id}")
    suspend fun getUser(@Path("id") id: String): UserDto
}

val api: UserApi = retrofit.create(UserApi::class.java)
// api 的运行时实现由 Retrofit 生成,调用方无需手写网络代理类。
示例 57:首次识别时才加载重型模型
kotlin 复制代码
class LazyTextRecognizer(
    private val factory: () -> TextRecognizer
) : TextRecognizer {
    private val delegate by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { factory() }
    override suspend fun recognize(image: ImageProxy): String = delegate.recognize(image)
}
示例 58:定位代理在访问前检查权限
kotlin 复制代码
class PermissionLocationProxy(
    private val context: Context,
    private val delegate: LocationService
) : LocationService {
    override suspend fun current(): AppLocation {
        check(context.hasLocationPermission()) { "缺少定位权限" }
        return delegate.current()
    }
}
示例 59:AIDL 根据 Binder 类型返回本地对象或代理
kotlin 复制代码
val service = IBookService.Stub.asInterface(binder)
val books = service.getBooks()

// asInterface 会根据 Binder 所在进程选择本地实现或生成的 Proxy。
示例 60:代理统一把存储访问切到 IO 调度器
kotlin 复制代码
class IoUserStoreProxy(
    private val delegate: UserStore,
    private val dispatcher: CoroutineDispatcher = Dispatchers.IO
) : UserStore {
    override suspend fun read(): UserPrefs = withContext(dispatcher) { delegate.read() }
    override suspend fun write(value: UserPrefs) = withContext(dispatcher) { delegate.write(value) }
}

三、行为型模式

13. 责任链模式(Chain of Responsibility)

编号 项目中的问题 可以考虑的模式 不要机械套用
61 网络请求需要依次经过日志、鉴权、重试等处理,并希望各处理器保持独立。 责任链模式、装饰器模式 OkHttp Interceptor 已提供责任链;注意 Interceptor 顺序、响应关闭和必须正确调用 proceed。
62 Deep Link 可能由内链、网页、活动页等多个处理器处理,命中后不再继续分派。 责任链模式 路由表加精确匹配往往更简单;处理器必须互斥且顺序明确,避免多个处理器同时响应。
63 数据读取需要按内存、磁盘、网络顺序尝试,前一级没有结果才进入下一级。 责任链模式 复杂缓存一致性应由 Repository 统筹;如果每级都必须执行,就不是"命中即终止"的责任链。
64 全局异常需要按登录失效、网络异常、业务异常等类型依次寻找可处理的处理器。 责任链模式 一个清晰的 when 加异常分类通常更易读;不要隐藏关键异常或让链尾悄悄吞错。
65 Android 触摸事件需要在父容器和子 View 之间分发,子 View 不处理时由其他节点继续处理。 责任链模式 这是系统已有事件分发机制,不要自行重写一套;先理解 dispatchTouchEvent、拦截和消费返回值。
示例 61:把鉴权作为 OkHttp 责任链中的一环
kotlin 复制代码
class AuthInterceptor(private val tokenStore: TokenStore) : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request().newBuilder()
            .addHeader("Authorization", "Bearer ${tokenStore.accessToken()}")
            .build()
        return chain.proceed(request)
    }
}
kotlin 复制代码
fun interface DeepLinkHandler { fun handle(uri: Uri): Boolean }

class DeepLinkRouter(private val handlers: List<DeepLinkHandler>) {
    fun open(uri: Uri): Boolean = handlers.any { handler -> handler.handle(uri) }
}
示例 63:依次尝试内存、磁盘和网络数据源
kotlin 复制代码
fun interface NewsFetcher { suspend fun fetch(): List<News>? }

class ChainedNewsFetcher(private val sources: List<NewsFetcher>) {
    suspend fun fetch(): List<News> {
        sources.forEach { source -> source.fetch()?.let { return it } }
        error("所有数据源都没有结果")
    }
}
示例 64:异常处理器只消费自己能够处理的异常
kotlin 复制代码
fun interface AppErrorHandler { fun handle(error: Throwable): Boolean }

class ErrorChain(private val handlers: List<AppErrorHandler>) {
    fun dispatch(error: Throwable) {
        if (handlers.none { it.handle(error) }) throw error
    }
}
示例 65:自定义 View 只消费自己处理的触摸事件
kotlin 复制代码
override fun onTouchEvent(event: MotionEvent): Boolean {
    return if (gestureDetector.onTouchEvent(event)) {
        true
    } else {
        super.onTouchEvent(event)
    }
}

14. 命令模式(Command)

编号 项目中的问题 可以考虑的模式 不要机械套用
66 文本或图片编辑器需要撤销、重做,并要求每个操作同时封装执行和反向执行逻辑。 命令模式 简单状态历史可以直接存快照;命令必须处理失败、合并连续操作和栈大小限制。
67 下载中心需要把开始、暂停、取消、重试统一放入队列,由执行器顺序处理。 命令模式、状态模式 WorkManager 等框架已有任务调度时优先复用;命令对象要可序列化或能恢复,不能只保存在内存。
68 遥控器、耳机按键或快捷键需要把不同按键映射到播放、暂停等动作。 命令模式 Kotlin 函数类型就是轻量命令;只有需要排队、日志、撤销或持久化时才需要完整命令对象。
69 离线时产生的修改需要保存为操作队列,网络恢复后按顺序同步到服务端。 命令模式 要处理幂等、冲突、过期和永久失败;不能简单认为"把请求重放一遍"就能保证数据一致。
70 批量操作需要把多个动作组合成一次操作,并支持统一执行或撤销。 命令模式、组合模式 批量操作不一定能原子撤销;执行一半失败时需要补偿策略,而不是假装全部回滚。
示例 66:用命令栈支持撤销和重做
kotlin 复制代码
interface EditCommand { fun execute(); fun undo() }

class CommandHistory {
    private val undoStack = ArrayDeque<EditCommand>()
    private val redoStack = ArrayDeque<EditCommand>()
    fun execute(command: EditCommand) {
        command.execute(); undoStack.addLast(command); redoStack.clear()
    }
    fun undo() = undoStack.removeLastOrNull()?.let { it.undo(); redoStack.addLast(it) }
    fun redo() = redoStack.removeLastOrNull()?.let { it.execute(); undoStack.addLast(it) }
}
示例 67:将下载动作建模为可排队命令
kotlin 复制代码
sealed interface DownloadCommand {
    val taskId: String
    data class Start(override val taskId: String) : DownloadCommand
    data class Pause(override val taskId: String) : DownloadCommand
    data class Cancel(override val taskId: String) : DownloadCommand
}

fun execute(command: DownloadCommand) = when (command) {
    is DownloadCommand.Start -> downloader.start(command.taskId)
    is DownloadCommand.Pause -> downloader.pause(command.taskId)
    is DownloadCommand.Cancel -> downloader.cancel(command.taskId)
}
示例 68:用函数类型实现轻量按键命令
kotlin 复制代码
class KeyCommandRegistry {
    private val commands = mutableMapOf<Int, () -> Unit>()
    fun bind(keyCode: Int, command: () -> Unit) { commands[keyCode] = command }
    fun onKey(keyCode: Int): Boolean = commands[keyCode]?.let { it(); true } ?: false
}

registry.bind(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE) { playbackController.toggle() }
示例 69:离线操作恢复后逐条执行
kotlin 复制代码
interface SyncCommand { suspend fun execute(): SyncOutcome }

suspend fun drainPendingCommands(queue: PendingCommandDao, parser: CommandParser) {
    queue.pendingInOrder().forEach { entity ->
        when (parser.decode(entity).execute()) {
            SyncOutcome.SUCCESS -> queue.delete(entity.id)
            SyncOutcome.RETRY_LATER -> return
            SyncOutcome.CONFLICT -> queue.markConflict(entity.id)
        }
    }
}
示例 70:把多个编辑命令组合成宏命令
kotlin 复制代码
class MacroCommand(private val commands: List<EditCommand>) : EditCommand {
    private val executed = mutableListOf<EditCommand>()
    override fun execute() = commands.forEach { it.execute(); executed += it }
    override fun undo() = executed.asReversed().forEach { it.undo() }
}

15. 解释器模式(Interpreter)

编号 项目中的问题 可以考虑的模式 不要机械套用
71 邮件或文件搜索支持 is:unread、before: 和逻辑组合,需要解析并执行一棵条件表达式树。 解释器模式 简单关键词搜索不需要 AST;语法复杂后优先使用成熟解析工具,并限制输入长度防止性能问题。
72 自动化任务允许用户组合"电量低于某值且连接 Wi-Fi"等简单条件。 解释器模式、组合模式 条件少时用数据类加 when 更容易维护;不要为了让用户写规则而执行任意脚本。
73 本地预览促销规则,需要解释满减、折扣和上限等表达式。 解释器模式、策略模式 最终价格必须由服务端权威计算;客户端解释器只用于预览,并要处理精度和规则版本。
74 计算器或公式输入需要把数字、运算符和括号解析为可求值的表达式。 解释器模式 不要让 eval 直接执行代码;要处理除零、数值溢出、非法输入和运算优先级。
75 远程配置需要按系统版本、渠道和用户分群组合功能开关条件。 解释器模式 能用结构化 JSON 条件表达就不要发明文本语言;客户端只解释白名单操作符,不使用动态代码执行。
示例 71:把搜索条件解释为表达式树
kotlin 复制代码
interface MailExpression { fun evaluate(mail: Mail): Boolean }
class UnreadExpression : MailExpression {
    override fun evaluate(mail: Mail) = !mail.isRead
}
class AndExpression(private val left: MailExpression, private val right: MailExpression) : MailExpression {
    override fun evaluate(mail: Mail) = left.evaluate(mail) && right.evaluate(mail)
}
// "is:unread AND before:2026-01-01" 经解析器生成 AndExpression 等节点。
示例 72:解释可组合的自动化条件
kotlin 复制代码
fun interface DeviceCondition { fun matches(state: DeviceState): Boolean }

val lowBattery = DeviceCondition { it.battery < 20 }
val onWifi = DeviceCondition { it.network == NetworkType.WIFI }
val rule = DeviceCondition { lowBattery.matches(it) && onWifi.matches(it) }
示例 73:将促销规则映射为可解释节点
kotlin 复制代码
sealed interface DiscountRule { fun preview(price: Long): Long }
data class PercentOff(val percent: Int) : DiscountRule {
    override fun preview(price: Long) = price * percent / 100
}
data class CapDiscount(val rule: DiscountRule, val max: Long) : DiscountRule {
    override fun preview(price: Long) = minOf(rule.preview(price), max)
}
示例 74:算术表达式节点负责求值
kotlin 复制代码
interface NumberExpression { fun eval(): Double }
data class Literal(val value: Double) : NumberExpression {
    override fun eval() = value
}
data class Add(val left: NumberExpression, val right: NumberExpression) : NumberExpression {
    override fun eval() = left.eval() + right.eval()
}
val result = Add(Literal(1.0), Literal(2.0)).eval()
示例 75:只解释白名单功能开关条件
kotlin 复制代码
sealed interface FeatureRule { fun matches(context: FeatureContext): Boolean }
data class MinSdk(val version: Int) : FeatureRule {
    override fun matches(context: FeatureContext) = context.sdkInt >= version
}
data class AllOf(val rules: List<FeatureRule>) : FeatureRule {
    override fun matches(context: FeatureContext) = rules.all { it.matches(context) }
}

16. 迭代器模式(Iterator)

编号 项目中的问题 可以考虑的模式 不要机械套用
76 网络分页结果需要逐条消费,调用方不希望关心页码和下一页请求细节。 迭代器模式、Flow 协程环境中 Flow 或 Paging 3 通常更自然;普通阻塞 Iterator 不能直接表达挂起加载和背压。
77 文件选择器需要深度遍历目录,但不希望把目录树结构暴露给上层。 迭代器模式 Kotlin sequence 和 File.walk() 已足够;遍历要防循环链接、权限失败和超大目录阻塞。
78 ContentResolver 或 SQLite 查询返回 Cursor,上层希望逐行读取而不关心游标位置。 迭代器模式 Cursor 本身已有迭代语义;必须 use 或关闭,并避免在主线程遍历大量数据。
79 自定义 View 树需要统一遍历所有节点,用于查找、调试或无障碍处理。 迭代器模式 小范围递归函数更直观;遍历中修改 View 层级要定义行为,避免并发修改。
80 聊天数据按日期和会话分组,但导出时希望按统一顺序遍历标题和消息节点。 迭代器模式、组合模式 如果只是一次扁平化,直接 flatMap 或 sequence 即可,不必手写迭代器类。
示例 76:用 Flow 封装分页拉取过程
kotlin 复制代码
fun pagedNews(api: NewsApi): Flow<News> = flow {
    var page = 0
    do {
        val result = api.page(page++)
        result.items.forEach { emit(it) }
    } while (result.hasNext)
}

pagedNews(api).collect { news -> render(news) }
示例 77:用 Sequence 隐藏目录遍历细节
kotlin 复制代码
fun File.descendantFiles(): Sequence<File> = sequence {
    if (isDirectory) {
        listFiles()?.forEach { child -> yieldAll(child.descendantFiles()) }
    } else {
        yield(this@descendantFiles)
    }
}
示例 78:安全地逐行读取 Cursor
kotlin 复制代码
resolver.query(uri, projection, null, null, null)?.use { cursor ->
    val nameIndex = cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)
    while (cursor.moveToNext()) {
        emitContact(cursor.getString(nameIndex))
    }
}
示例 79:统一遍历 View 与子 View
kotlin 复制代码
fun View.depthFirst(): Sequence<View> = sequence {
    yield(this@depthFirst)
    if (this@depthFirst is ViewGroup) {
        for (index in 0 until childCount) yieldAll(getChildAt(index).depthFirst())
    }
}
示例 80:按展示顺序遍历聊天分组节点
kotlin 复制代码
fun List<MessageGroup>.asDisplayNodes(): Sequence<DisplayNode> = sequence {
    this@asDisplayNodes.forEach { group ->
        yield(DisplayNode.DateHeader(group.date))
        group.messages.forEach { yield(DisplayNode.MessageItem(it)) }
    }
}

17. 中介者模式(Mediator)

编号 项目中的问题 可以考虑的模式 不要机械套用
81 登录或注册表单中输入框、协议勾选、错误提示和提交按钮互相引用,交互逻辑难以维护。 中介者模式、观察者模式 ViewModel 加单一 UI State 往往更清晰;不要让 Mediator 直接持有大量 View 引用形成新的 God Object。
82 播放页面、播放 Service、通知栏和耳机控制需要共享状态并协调动作。 中介者模式、观察者模式 MediaSession 已承担不少协调职责,应优先复用;不要把所有播放细节都复制到一个中介类。
83 聊天页的输入框、键盘、表情面板、更多功能面板互相影响,打开一个时需要关闭另一个。 中介者模式、状态模式 面板状态可用一个密封状态表达;复杂时再由协调器处理窗口 Insets 和焦点。
84 多 Fragment 页面需要选择列表项后更新详情,同时同步标题、按钮和导航状态。 中介者模式、观察者模式 共享 ViewModel 或导航状态通常就是更轻量的协调方式,不要让 Fragment 互相直接引用。
85 首页刷新时刷新头、加载列表、空视图和错误视图需要统一切换,当前代码四处手动控制。 中介者模式、状态模式 最好用一个不可变 UI State 驱动渲染;中介者只负责协调,不应继续堆积业务请求。
示例 81:ViewModel 作为表单状态协调者
kotlin 复制代码
class LoginViewModel : ViewModel() {
    val account = MutableStateFlow("")
    val password = MutableStateFlow("")
    val agreement = MutableStateFlow(false)

    val canSubmit = combine(account, password, agreement) { a, p, agreed ->
        a.isNotBlank() && p.length >= 6 && agreed
    }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), false)
}
示例 82:统一协调播放动作来源
kotlin 复制代码
class PlaybackMediator(private val session: MediaSessionCompat) {
    fun play() = session.controller.transportControls.play()
    fun pause() = session.controller.transportControls.pause()

    fun onHeadsetButton() = pause()
    fun onNotificationAction(action: String) = if (action == ACTION_PAUSE) pause() else play()
}
示例 83:集中管理聊天面板互斥状态
kotlin 复制代码
enum class ChatPanel { NONE, KEYBOARD, EMOJI, MORE }

class ChatPanelCoordinator {
    val panel = MutableStateFlow(ChatPanel.NONE)
    fun showEmoji() { panel.value = ChatPanel.EMOJI }
    fun showMore() { panel.value = ChatPanel.MORE }
    fun showKeyboard() { panel.value = ChatPanel.KEYBOARD }
}
示例 84:用共享 ViewModel 协调列表和详情 Fragment
kotlin 复制代码
class MasterDetailViewModel : ViewModel() {
    private val _selectedId = MutableStateFlow<String?>(null)
    val selectedId: StateFlow<String?> = _selectedId.asStateFlow()

    fun select(id: String) { _selectedId.value = id }
}
// 列表只调用 select,详情只观察 selectedId,二者不直接引用。
示例 85:由统一 UI State 协调多个视图
kotlin 复制代码
data class HomeUiState(
    val loading: Boolean = false,
    val items: List<HomeItem> = emptyList(),
    val error: String? = null
)

fun render(state: HomeUiState) = with(binding) {
    swipeRefresh.isRefreshing = state.loading
    emptyView.isVisible = !state.loading && state.items.isEmpty() && state.error == null
    errorView.isVisible = state.error != null
    adapter.submitList(state.items)
}

18. 备忘录模式(Memento)

编号 项目中的问题 可以考虑的模式 不要机械套用
86 编辑器需要保存某些时间点的完整状态,用户可以随时恢复到检查点。 备忘录模式 小改动可用命令记录差量;快照会消耗内存,要限制数量并避免保存大 Bitmap 的重复副本。
87 复杂表单在旋转、配置变化或进程重建后需要恢复,而不希望 ViewModel 重新请求全部数据。 备忘录模式、SavedStateHandle 优先使用 SavedStateHandle、SavedStateRegistry 和持久化存储;Bundle 不能保存超大对象或敏感明文。
88 游戏或互动课程需要保存关卡检查点,退出后继续时恢复角色、进度和临时状态。 备忘录模式 快照需要版本号和兼容策略;游戏数据量大时应持久化必要状态,而不是序列化整个对象图。
89 图片编辑的裁剪、滤镜等步骤需要保存检查点,支持回退到任意一步。 备忘录模式、命令模式 保存参数和操作序列通常比保存每步 Bitmap 更省内存;还要考虑后台恢复和草稿清理。
90 音视频应用需要定期保存播放列表、媒体位置和播放速度,重启后恢复现场。 备忘录模式 只保存可序列化的业务状态,不保存 Player、Surface 或 Binder 等框架对象。
示例 86:编辑器创建并恢复检查点
kotlin 复制代码
data class EditorSnapshot(val text: String, val cursor: Int)

class Editor {
    private var state = EditorSnapshot("", 0)
    fun save(): EditorSnapshot = state
    fun restore(snapshot: EditorSnapshot) { state = snapshot }
}
示例 87:使用 SavedStateHandle 保存表单草稿
kotlin 复制代码
class FormViewModel(private val state: SavedStateHandle) : ViewModel() {
    val draft = state.getStateFlow(KEY_DRAFT, FormDraft())
    fun onDraftChanged(value: FormDraft) { state[KEY_DRAFT] = value }

    private companion object { const val KEY_DRAFT = "draft" }
}
// FormDraft 需要按 SavedState 支持的方式进行序列化。
示例 88:保存带版本号的游戏快照
kotlin 复制代码
@Serializable
data class GameSnapshot(
    val version: Int = 1,
    val level: Int,
    val playerHp: Int,
    val checkpointId: String
)

suspend fun save(game: GameSnapshot) = dataStore.updateData { game }
示例 89:图片编辑历史保存参数而不是 Bitmap
kotlin 复制代码
data class EditSnapshot(val operations: List<EditOperation>)

class EditHistory {
    private val snapshots = ArrayDeque<EditSnapshot>()
    fun checkpoint(current: EditSnapshot) { snapshots.addLast(current) }
    fun restoreLast(): EditSnapshot? = snapshots.removeLastOrNull()
}
示例 90:持久化播放现场
kotlin 复制代码
@Serializable
data class PlaybackSnapshot(
    val mediaId: String,
    val positionMs: Long,
    val speed: Float
)

suspend fun restorePlayback(store: PlaybackSnapshotStore, controller: PlaybackController) {
    val saved = store.read() ?: return
    controller.prepare(saved.mediaId, saved.positionMs, saved.speed)
}

19. 观察者模式(Observer)

编号 项目中的问题 可以考虑的模式 不要机械套用
91 ViewModel 的页面状态需要持续通知 UI,页面销毁后又要避免无效更新和内存泄漏。 观察者模式、Flow 优先 StateFlow 加生命周期感知收集;不要长期持有 Activity 回调或手动维护脆弱监听器列表。
92 下载任务进度需要同时展示在下载列表、详情页和通知栏。 观察者模式、组合模式 状态应由下载中心统一拥有;通知栏更新要节流,UI 只观察状态,不应各自修改任务进度。
93 网络连接状态变化需要被多个功能模块接收,网络恢复后还可能触发同步。 观察者模式、责任链模式 系统回调要转换为安全的 Flow 并注销;不要仅凭一次"已连接"回调就认定互联网一定可用。
94 数据库内容变化后,列表、统计数字和详情页需要随之更新。 观察者模式 Room 已能返回 Flow;不要用事件总线重复通知所有页面手动刷新数据库。
95 Toast、导航等一次性事件需要从 ViewModel 发送给 UI,但不希望屏幕旋转后反复执行。 观察者模式、SharedFlow StateFlow 适合可重复获得的状态,一次性事件要单独建模;事件丢失、缓冲和导航恢复都要验证。
示例 91:用 StateFlow 和生命周期感知收集更新 UI
kotlin 复制代码
class NewsViewModel : ViewModel() {
    private val _uiState = MutableStateFlow(NewsUiState())
    val uiState: StateFlow<NewsUiState> = _uiState.asStateFlow()
}

viewLifecycleOwner.lifecycleScope.launch {
    viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
        viewModel.uiState.collect(::render)
    }
}
示例 92:多个观察者共享统一下载进度
kotlin 复制代码
class DownloadProgressStore {
    private val _progress = MutableStateFlow<Map<String, Int>>(emptyMap())
    val progress: StateFlow<Map<String, Int>> = _progress.asStateFlow()

    fun update(taskId: String, value: Int) {
        _progress.update { it + (taskId to value.coerceIn(0, 100)) }
    }
}
示例 93:把 ConnectivityManager 回调转换为 Flow
kotlin 复制代码
fun connectivityFlow(manager: ConnectivityManager): Flow<Boolean> = callbackFlow {
    val callback = object : ConnectivityManager.NetworkCallback() {
        override fun onAvailable(network: Network) { trySend(true) }
        override fun onLost(network: Network) { trySend(false) }
    }
    manager.registerDefaultNetworkCallback(callback)
    awaitClose { manager.unregisterNetworkCallback(callback) }
}.distinctUntilChanged()
示例 94:直接观察 Room 数据变化
kotlin 复制代码
@Dao
interface ArticleDao {
    @Query("SELECT * FROM articles ORDER BY publishedAt DESC")
    fun observeArticles(): Flow<List<ArticleEntity>>
}

val articles = articleDao.observeArticles().map { list -> list.map(ArticleEntity::toDomain) }
示例 95:用 SharedFlow 表达一次性 UI 事件
kotlin 复制代码
sealed interface UiEvent {
    data class ShowMessage(val text: String) : UiEvent
    data class Navigate(val route: String) : UiEvent
}

private val _events = MutableSharedFlow<UiEvent>()
val events: SharedFlow<UiEvent> = _events.asSharedFlow()

fun onSaveSucceeded() { _events.tryEmit(UiEvent.ShowMessage("保存成功")) }

20. 状态模式(State)

编号 项目中的问题 可以考虑的模式 不要机械套用
96 播放器在空闲、准备中、播放、暂停和错误状态下允许的操作不同,条件判断散落。 状态模式 状态数量少时密封类加集中 when 更直观;不要让各状态对象随意持有或创建播放器依赖。
97 下载任务包含等待、运行、暂停、成功、失败和取消状态,按钮行为及合法迁移不同。 状态模式、命令模式 WorkManager 或下载中心应拥有状态权威来源;UI 状态不要反过来决定真实任务状态。
98 录音器只有特定状态下才能开始、暂停、继续和停止,错误调用经常导致异常。 状态模式 不要只把 if 搬入很多状态类;集中定义迁移表、线程约束和资源释放顺序。
99 蓝牙设备经历断开、扫描、连接中、已连接和绑定失败等状态,UI 与操作依赖当前状态。 状态模式、观察者模式 系统回调可能乱序或重复,状态迁移要幂等;不要只在 UI 中保存连接状态。
100 登录流程根据未登录、需要验证码、需要补资料、已登录等状态展示不同页面和可用操作。 状态模式、策略模式 简单导航用密封状态和 when 即可;令牌刷新等临时状态不应与长期账户状态混为一谈。
示例 96:集中定义播放器状态和允许的操作
kotlin 复制代码
sealed interface PlaybackState {
    data object Idle : PlaybackState
    data object Preparing : PlaybackState
    data object Playing : PlaybackState
    data class Error(val cause: Throwable) : PlaybackState
}

fun canPause(state: PlaybackState): Boolean = state is PlaybackState.Playing
示例 97:用 reducer 明确下载状态迁移
kotlin 复制代码
fun DownloadState.reduce(event: DownloadEvent): DownloadState = when (this) {
    DownloadState.Idle -> if (event is Start) DownloadState.Running else this
    DownloadState.Running -> when (event) {
        is Pause -> DownloadState.Paused
        is Complete -> DownloadState.Success
        is Fail -> DownloadState.Failed(event.cause)
        else -> this
    }
    else -> this
}
示例 98:录音操作只执行合法状态迁移
kotlin 复制代码
fun RecorderState.start(): RecorderState = when (this) {
    RecorderState.Idle -> RecorderState.Recording
    else -> error("当前状态 $this 不能开始录音")
}

fun RecorderState.stop(): RecorderState = when (this) {
    RecorderState.Recording, RecorderState.Paused -> RecorderState.Idle
    else -> error("当前状态 $this 不能停止录音")
}
示例 99:将蓝牙回调统一转换为状态事件
kotlin 复制代码
sealed interface BleState {
    data object Disconnected : BleState
    data object Connecting : BleState
    data class Connected(val deviceId: String) : BleState
    data class Failed(val reason: String) : BleState
}

fun onConnectionLost(state: BleState): BleState = when (state) {
    is BleState.Connected, BleState.Connecting -> BleState.Disconnected
    else -> state // 重复或迟到的断连回调保持幂等
}
示例 100:用密封状态驱动登录导航
kotlin 复制代码
sealed interface AuthState {
    data object LoggedOut : AuthState
    data class NeedOtp(val phone: String) : AuthState
    data class NeedProfile(val token: String) : AuthState
    data class LoggedIn(val account: Account) : AuthState
}

fun routeFor(state: AuthState): String = when (state) {
    AuthState.LoggedOut -> "login"
    is AuthState.NeedOtp -> "otp"
    is AuthState.NeedProfile -> "profile"
    is AuthState.LoggedIn -> "home"
}

21. 策略模式(Strategy)

编号 项目中的问题 可以考虑的模式 不要机械套用
101 缓存需要按 TTL、LRU 或业务规则选择不同淘汰方式,分支随规则增加。 策略模式 Android LruCache 等现成实现先复用;只有少量规则时传入函数或配置比新增类体系简单。
102 图片上传前需要按场景选择 JPEG、WebP、质量或缩放算法。 策略模式、工厂方法模式 格式参数化通常就够了;压缩策略要注意尺寸、EXIF、耗时和主线程问题。
103 支付页面支持多种支付方式,每种方式的调起、参数和结果处理不同。 策略模式、适配器模式 支付方式应使用稳定注册表而不是散落的 when;支付结果仍以服务端确认为准。
104 网络重试需要固定间隔、指数退避或带随机抖动的不同策略。 策略模式 函数类型足以表达延迟计算;策略不应绕过协程取消,也不能对非幂等请求默认重试。
105 信息流需要按时间、热度或本地推荐规则排序,并能在实验中切换。 策略模式 Kotlin Comparator、比较器函数或普通高阶函数已经是轻量策略,无需强制创建接口。
示例 101:把缓存有效性判断注入为策略
kotlin 复制代码
fun interface CacheValidityStrategy {
    fun isValid(entry: CacheEntry, now: Long): Boolean
}

class TtlValidity(private val ttlMs: Long) : CacheValidityStrategy {
    override fun isValid(entry: CacheEntry, now: Long) = now - entry.savedAt < ttlMs
}
示例 102:按上传场景选择图片压缩策略
kotlin 复制代码
fun interface ImageCompressionStrategy {
    suspend fun compress(source: File): File
}

class JpegCompression(private val quality: Int) : ImageCompressionStrategy {
    override suspend fun compress(source: File): File = withContext(Dispatchers.IO) {
        source.decodeBitmap().writeJpeg(quality)
    }
}
示例 103:使用注册表选择支付策略
kotlin 复制代码
interface PaymentStrategy { suspend fun pay(order: Order): PaymentResult }

class PaymentRegistry(strategies: Map<PaymentMethod, PaymentStrategy>) {
    private val strategies = strategies.toMap()
    fun method(method: PaymentMethod): PaymentStrategy =
        checkNotNull(strategies[method]) { "不支持 $method" }
}
示例 104:用函数类型表达退避策略
kotlin 复制代码
fun interface BackoffStrategy { fun delayFor(attempt: Int): Long }

val exponential = BackoffStrategy { attempt ->
    (1_000L shl attempt).coerceAtMost(30_000L)
}
val fixed = BackoffStrategy { 2_000L }
示例 105:Comparator 就是轻量排序策略
kotlin 复制代码
enum class FeedSort { TIME, HOT }

fun comparatorFor(sort: FeedSort): Comparator<Post> = when (sort) {
    FeedSort.TIME -> compareByDescending(Post::publishedAt)
    FeedSort.HOT -> compareByDescending(Post::hotScore)
}

val sorted = posts.sortedWith(comparatorFor(FeedSort.HOT))

22. 模板方法模式(Template Method)

编号 项目中的问题 可以考虑的模式 不要机械套用
106 多类数据加载都遵循"加载前检查、获取数据、统一处理结果"的固定骨架,只有获取方式不同。 模板方法模式、策略模式 继承不是默认答案;传入 fetch 函数或组合 Repository 通常更灵活,也更便于测试。
107 多个 Worker 都需要执行相同的前置日志、异常归类和结果包装,只改变核心任务。 模板方法模式 不要为了复用几行代码形成很深基类;横切能力也可通过装饰器或公共函数实现。
108 多个列表 Adapter 的创建流程一致,只有布局与绑定 Item 的逻辑不同。 模板方法模式 ListAdapter 已提供不少模板扩展点;复杂基类容易隐藏 DiffUtil、ViewType 和生命周期行为。
109 报表生成固定包含头部、正文和尾部,不同报表只改变正文生成方式。 模板方法模式、建造者模式 步骤可自由组合时应使用组合或函数参数,而不是把顺序硬编码进基类。
110 自定义图表 View 都要完成画布检查、坐标转换和裁剪,再绘制不同图形。 模板方法模式 绘制性能优先,模板调用不应引入大量对象分配;简单图表可直接在一个 View 中组织函数。
示例 106:固定加载骨架,延迟具体获取步骤
kotlin 复制代码
abstract class BaseLoader<T> {
    protected abstract suspend fun fetch(): T

    suspend fun load(): T {
        onStart()
        return fetch().also(::onLoaded)
    }
    protected open fun onStart() = Unit
    protected open fun onLoaded(value: T) = Unit
}
示例 107:Worker 基类统一包装核心任务
kotlin 复制代码
abstract class BaseWorker(context: Context, params: WorkerParameters) :
    CoroutineWorker(context, params) {

    protected abstract suspend fun work(): Result

    final override suspend fun doWork(): Result = try {
        work()
    } catch (error: IOException) {
        Result.retry()
    }
}
示例 108:Adapter 固定创建流程并暴露绑定步骤
kotlin 复制代码
abstract class BaseItemAdapter<T> : RecyclerView.Adapter<BindingViewHolder>() {
    abstract fun bind(holder: BindingViewHolder, item: T)
    abstract fun itemAt(position: Int): T

    final override fun onBindViewHolder(holder: BindingViewHolder, position: Int) {
        bind(holder, itemAt(position))
    }
}
示例 109:固定报表步骤并允许替换正文
kotlin 复制代码
abstract class ReportGenerator {
    protected abstract fun body(): String

    fun generate(): String = buildString {
        appendLine(header())
        appendLine(body())
        appendLine(footer())
    }
    protected open fun header() = "报表"
    protected open fun footer() = "生成时间:${System.currentTimeMillis()}"
}
示例 110:自定义 View 保留公共绘制骨架
kotlin 复制代码
abstract class BaseChartView(context: Context) : View(context) {
    protected abstract fun drawChart(canvas: Canvas)

    final override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        if (width == 0 || height == 0) return
        canvas.withClipRect(paddingLeft, paddingTop, width - paddingRight, height - paddingBottom) {
            drawChart(this)
        }
    }
}

23. 访问者模式(Visitor)

编号 项目中的问题 可以考虑的模式 不要机械套用
111 Android Lint 需要遍历稳定的 UAST/AST 节点,并不断新增不同代码检查规则。 访问者模式 框架已有 Scanner/Visitor 扩展点,按 API 使用即可;普通业务列表处理不需要模仿 AST 访问者。
112 富文本节点类型稳定,但需要不断增加渲染、纯文本导出、字数统计等操作。 访问者模式、迭代器模式 Kotlin 密封类加 when 通常更简洁;只有"类型稳定、操作频繁增加"时访问者才更有优势。
113 聊天消息类型稳定,需要分别生成无障碍描述、分享文本和调试摘要。 访问者模式 消息类型经常增加时,每个访问者都要修改;少量操作用扩展函数或 when 更易读。
114 绘图命令类型稳定,但同一命令树需要分别输出 Canvas、SVG 或统计信息。 访问者模式、解释器模式 不要在绘制每帧时创建大量 Visitor 和节点对象;优先考虑性能与直接遍历。
115 自定义 UI 描述树需要执行序列化、脱敏日志和布局检查,节点类型相对固定。 访问者模式、组合模式 Compose 的真实 UI 树不应随意再复制一套;仅在已有自定义文档或声明式模型时考虑。
示例 111:利用 Lint 的 UAST 访问机制编写检查
kotlin 复制代码
class LogDetector : Detector(), Detector.UastScanner {
    override fun getApplicableUastTypes() = listOf(UCallExpression::class.java)

    override fun createUastHandler(context: JavaContext) = object : UElementHandler() {
        override fun visitCallExpression(node: UCallExpression) {
            if (node.methodName == "println") {
                context.report(ISSUE, node, context.getLocation(node), "请使用统一日志工具")
            }
        }
    }
}
示例 112:为富文本节点增加纯文本导出操作
kotlin 复制代码
interface RichNodeVisitor<T> {
    fun visitText(node: TextNode): T
    fun visitImage(node: ImageNode): T
}
sealed interface RichNode { fun <T> accept(visitor: RichNodeVisitor<T>): T }

object PlainTextVisitor : RichNodeVisitor<String> {
    override fun visitText(node: TextNode) = node.text
    override fun visitImage(node: ImageNode) = "[图片:${node.alt}]"
}
示例 113:统一生成消息的无障碍描述
kotlin 复制代码
interface MessageVisitor<T> {
    fun text(message: TextMessage): T
    fun image(message: ImageMessage): T
}

class AccessibilityVisitor : MessageVisitor<String> {
    override fun text(message: TextMessage) = "${message.sender} 说:${message.content}"
    override fun image(message: ImageMessage) = "${message.sender} 发来一张图片"
}
示例 114:为绘图命令增加 SVG 输出访问者
kotlin 复制代码
interface DrawVisitor {
    fun visitLine(line: DrawLine)
    fun visitCircle(circle: DrawCircle)
}

class SvgVisitor : DrawVisitor {
    override fun visitLine(line: DrawLine) { output += "<line ... />" }
    override fun visitCircle(circle: DrawCircle) { output += "<circle ... />" }
}
示例 115:为自定义 UI 节点增加脱敏日志操作
kotlin 复制代码
interface UiNodeVisitor<T> { fun visitField(node: FieldNode): T; fun visitGroup(node: GroupNode): T }

class RedactedLogVisitor : UiNodeVisitor<String> {
    override fun visitField(node: FieldNode) = "${node.name}=***"
    override fun visitGroup(node: GroupNode) = node.children.joinToString { it.accept(this) }
}

四、综合场景:一个问题可以有多种合理方案

编号 项目中的问题 可以考虑的模式 不要机械套用
116 国内和海外推送实现不同,业务层只想订阅主题和接收统一消息,还要支持无推送的测试环境。 抽象工厂、适配器、外观、空对象 不要把所有模式都实现一遍;通常依赖注入加统一接口和空实现已经足够。
117 新闻列表需要先展示缓存,再刷新网络;失败时重试,数据库更新后多个页面同步刷新。 观察者、装饰器、策略、责任链 Repository 加 Room Flow 往往已能解决;重试、缓存和同步职责要分清,不能全塞进一个类。
118 下载中心需要排队命令、合法状态迁移、进度观察、通知栏和断点恢复。 命令、状态、观察者、外观 先确定下载状态的唯一拥有者和持久化方案;模式不能替代 WorkManager、文件 IO 和生命周期设计。
119 富文本编辑器需要撤销重做、草稿恢复、不同导出格式和输入规则。 命令、备忘录、访问者、策略 小编辑器不要同时上四套抽象;先确定文档模型,再根据真实需求逐项引入。
120 登录模块支持账号、扫码和第三方登录,需要统一结果、统计、埋点隔离和测试空实现。 策略、适配器、外观、组合、空对象 登录安全、令牌存储和异常语义比模式数量更重要;简单项目用依赖注入加几个接口即可。
示例 116:统一推送接口,用空实现支持测试环境
kotlin 复制代码
interface PushService { suspend fun subscribe(topic: String) }

object NoOpPushService : PushService {
    override suspend fun subscribe(topic: String) = Unit
}

class PushFacade(private val service: PushService) {
    suspend fun enableNews() = service.subscribe("news")
}
// VendorPushAdapter 负责厂商 API 转换,依赖注入决定提供 Vendor 实现或 NoOp。
示例 117:Room Flow 观察缓存,Repository 负责刷新
kotlin 复制代码
fun observeNews(): Flow<List<News>> = dao.observeAll().map { it.toDomain() }

suspend fun refresh() {
    val remote = retry { api.fetchNews() }
    dao.replaceAll(remote.toEntity()) // Room 自动通知所有观察者
}
示例 118:下载命令只改变状态,进度通过 Flow 对外暴露
kotlin 复制代码
class DownloadCenter {
    private val _states = MutableStateFlow<Map<String, DownloadState>>(emptyMap())
    val states: StateFlow<Map<String, DownloadState>> = _states.asStateFlow()

    suspend fun dispatch(command: DownloadCommand) {
        val old = _states.value[command.taskId] ?: DownloadState.Idle
        _states.update { it + (command.taskId to old.reduce(command.toEvent())) }
        executor.execute(command)
    }
}
示例 119:编辑器以文档模型为核心组合命令和快照
kotlin 复制代码
class RichTextEditor {
    private var document = RichDocument.empty()
    private val history = CommandHistory()

    fun apply(command: EditCommand) = history.execute(command)
    fun saveDraft(): EditorSnapshot = document.toSnapshot()
    fun restore(snapshot: EditorSnapshot) { document = snapshot.toDocument() }
    fun export(visitor: RichNodeVisitor<String>) = document.nodes.joinToString { it.accept(visitor) }
}
示例 120:登录策略适配不同 SDK,门面统一结果和埋点
kotlin 复制代码
interface LoginStrategy { suspend fun login(): Result<AppAccount> }

class LoginFacade(
    private val strategies: Map<LoginType, LoginStrategy>,
    private val tracker: AnalyticsTracker
) {
    suspend fun login(type: LoginType): Result<AppAccount> =
        checkNotNull(strategies[type]).login().also { result ->
            tracker.track(LoginResultEvent(type, result.isSuccess))
        }
}

附录:23 种模式与问题编号速查

分类 模式 问题编号
创建型 单例、建造者、工厂方法、抽象工厂、原型 1~5、6~10、11~15、16~20、21~25
结构型 适配器、桥接、组合、装饰器、外观、享元、代理 26~30、31~35、36~40、41~45、46~50、51~55、56~60
行为型 责任链、命令、解释器、迭代器、中介者、备忘录 61~65、66~70、71~75、76~80、81~85、86~90
行为型 观察者、状态、策略、模板方法、访问者 91~95、96~100、101~105、106~110、111~115
综合 多模式综合练习 116~120

最后的自检问题

每次准备引入某个模式时,至少再问一遍:

  • 当前问题能否用一个函数、数据类、密封类或依赖注入解决?
  • 这个变化是真实需求,还是仅为想象中的未来需求?
  • 新方案是否减少了修改范围,而不只是增加了接口和类?
  • 是否能通过新增需求或替换实现验证抽象的价值?
  • 新同事能否快速理解?测试是否更容易?
  • 如果答案不明确,能否先保留简单实现,等变化出现后再重构?
相关推荐
xcLeigh11 分钟前
Go入门:逻辑运算符与短路求值机制
android·java·golang·go·教程
楚识科技1 小时前
移动端 OCR SDK 集成拆解:Android/iOS 离线识别与结构化回填
android·ios·ocr
应用市场1 小时前
安卓底层拆解(五)· user 版的 adb 授权与 RSA 密钥
android·adb
默 语10 小时前
HarmonyOS7 事件分发控制(二):onTouchIntercept 镂空玻璃卡——圆内自己接,圆外放行
android·java·开发语言
CocoaKier12 小时前
因 Google Ads 投流图片太暴露,险些导致谷歌包被下架
android·google
HZero.chen13 小时前
从 APK 到 APEX:以 PermissionController 为例拆解 Android 模块化演进与部署实战
android
你看我名字16 小时前
OpenAI 兼容接口能不能直接接入:数眼智能大模型 API 迁移实战与兼容性检查
android·java·数据库·大模型平台选择
用户693717500138417 小时前
用上 AI 之后,Android 的边界确实在消失,但我的活反而变多了
android·人工智能·ai编程
AI2中文网17 小时前
App Inventor 做的表单怎么导出 PDF?WebViewer + JavaScript 在本地生成并保存 PDF 的完整示例
android·开发语言·javascript·pdf·鸿蒙·app inventor