设计模式-适配器adapter

2020-10-08  本文已影响0人  Sweet丶

这里介绍一下设计模式中的适配器模式在iOS中的实现。

适配器模式解释
意图是将一个类A的接口转换成另一个类B的接口,使得我们使用时面向类B就能兼容到类A的功能,比如美国电器 110V,中国 220V,就要有一个适配器将 110V 转化为 220V,电器只要连接这个适配器就可以。

下面是一个例子:

我们的一个播放器AudioPlayer只能播放MP3,另一个播放器AdvancedMediaPlayer能播放MP4和vlc文件,现在要实现在使用AudioPlayer时,如果打开的是MP4和vlc文件也能播放。

  1. 能播放MP3之外的播放器的类VlcPlayerMp4Player
protocol AdvancedMediaPlayer : class {
    func playVlc(fileName : String)
    func playMP4(fileName : String)
}

extension AdvancedMediaPlayer {
    func playVlc(fileName : String) {}
    func playMP4(fileName : String) {}
}

@objcMembers
class VlcPlayer: NSObject, AdvancedMediaPlayer {
    func playVlc(fileName: String) {
        print("Playing vlc file named \(fileName)")
    }
}
@objcMembers
class Mp4Player:NSObject, AdvancedMediaPlayer {
    func playMP4(fileName : String) {
        print("Playing MP4 file named \(fileName)")
    }
}
  1. 适配器类的设计
// 设计适配器的接口
protocol MediaPlayer : class {
    func play(audioType : String?, fileName : String)
}

// 适配器
@objcMembers
class MediaAdapter:NSObject, MediaPlayer {
    var advancedPlayer : AdvancedMediaPlayer?
    
    init(audioType : String) {
        if audioType == "vlc" {
            self.advancedPlayer = VlcPlayer.init()
        }else if audioType == "mp4" {
            self.advancedPlayer = Mp4Player.init()
        }else {
            self.advancedPlayer = nil
        }
    }
    
    func play(audioType: String?, fileName: String) {
        if audioType == "vlc" {
            advancedPlayer?.playVlc(fileName: fileName)
        }else if audioType == "mp4" {
            advancedPlayer?.playMP4(fileName: fileName)
        }
    }
}
  1. MP3播放器类
// MP3播放器
@objcMembers
class AudioPlayer:NSObject, MediaPlayer {
    
    func play(audioType: String?, fileName: String) {
        if audioType == "mp3" {
            print("Playing mp3 file named \(fileName)")
        }else if audioType == "vlc" || audioType == "mp4" {
            let adapter = MediaAdapter.init(audioType: audioType!)
            adapter.play(audioType: audioType, fileName: fileName)
        }else{
            print("unsupport audioType file")
        }
    }
}
  1. 使用时
AudioPlayer *player = [[AudioPlayer alloc] init];
[player playWithAudioType:@"mp3" fileName:@"mp3_filename"];
[player playWithAudioType:@"mp4" fileName:@"mp4_filename"];
[player playWithAudioType:@"vlc" fileName:@"vlc_filename"];
[player playWithAudioType:@"unsupport" fileName:@"unsupport_filename"];
上一篇下一篇

猜你喜欢

热点阅读