go 示例
最后更新于:2022-04-02 04:19:39
[TOC]
## 示例
### 音乐播放器适配
输出 ``` play sound: game.mp3 ```
';
main.go
``` package main import "fmt" // 播放接口 type Player interface { PlayMusic() } // 音乐播放器 type MusicPlayer struct { Src string } func (p MusicPlayer) PlayMusic() { fmt.Println("play music: " + p.Src) } // 游戏音乐播放器 type GameSoundPlayer struct { Src string } func (p GameSoundPlayer) PlaySound() { fmt.Println("play sound: " + p.Src) } // 使游戏音乐播放器适配音乐播放器 type GameSoundPlayerAdapter struct{ SoundPlayer GameSoundPlayer } func (g GameSoundPlayerAdapter) PlayMusic(){ g.SoundPlayer.PlaySound() } func main() { player :=GameSoundPlayer{Src:"game.mp3"} playerApater := GameSoundPlayerAdapter {SoundPlayer:player} play(playerApater) } func play(player Player) { player.PlayMusic() } ```输出 ``` play sound: game.mp3 ```