适配器模式

发布于:2025-07-15 ⋅ 阅读:(12) ⋅ 点赞:(0)

适配器模式解析

适配器模式类似于生活中的电源适配器:

  • 手机充电器使用USB接口
  • 墙壁插座采用圆形接口
  • 适配器充当两者间的连接桥梁

在编程中,适配器模式使不兼容的接口能够协同工作。

示例场景

假设存在两个不同的音频系统:

// 系统A:传统音频播放器
interface OldAudioPlayer {
    fun playMusic(fileName: String)
    fun stopMusic()
}

// 系统B:现代语音合成器
interface NewSpeechSynthesizer {
    fun speakText(text: String)
    fun setVoice(voice: String)
    fun stopSpeaking()
}

统一接口需求

// 期望的统一接口
interface AudioProcessor {
    fun play(source: String)
    fun stop()
}

适配器实现方案

// 传统播放器适配器
class OldPlayerAdapter(private val oldPlayer: OldAudioPlayer) : AudioProcessor {
    override fun play(source: String) {
        oldPlayer.playMusic(source)
    }
    
    override fun stop() {
        oldPlayer.stopMusic()
    }
}

// 现代合成器适配器
class NewSynthesizerAdapter(private val newSynthesizer: NewSpeechSynthesizer) : AudioProcessor {
    override fun play(source: String) {
        newSynthesizer.speakText(source)
    }
    
    override fun stop() {
        newSynthesizer.stopSpeaking()
    }
}

统一调用示例

fun useAudio() {
    val oldPlayer = OldAudioPlayer()
    val newSynthesizer = NewSpeechSynthesizer()
    
    // 通过适配器统一调用
    val processor1: AudioProcessor = OldPlayerAdapter(oldPlayer)
    val processor2: AudioProcessor = NewSynthesizerAdapter(newSynthesizer)
    
    // 标准化操作
    processor1.play("music.mp3")  // 播放音频
    processor2.play("你好世界")    // 语音合成
}

网站公告

今日签到

点亮在社区的每一天
去签到