以下是使用 Python 实现一个简单的 CD 播放器播放管理的示例代码,使用了模式迁移的设计思想: ```python class CDPlayer: def __init__(self): self.power = False self.cd_loaded = False self.playing = False self.current_track = 1 def power_button(self): if not self.power: self.power = True print("电源已打开") else: self.power = False print("电源已关闭") def eject_button(self): if self.power and self.cd_loaded: self.cd_loaded = False print("CD 已弹出") else: print("操作无效") def load_button(self): if self.power and not self.cd_loaded: self.cd_loaded = True print("CD 已装入") else: print("操作无效") def play_button(self): if self.power and self.cd_loaded and not self.playing: self.playing = True print("开始播放") elif self.power and self.cd_loaded and self.playing: self.playing = False print("已暂停播放") else: print("操作无效") def previous_button(self): if self.power and self.cd_loaded: if self.current_track > 1: self.current_track -= 1 print(f"播放前一曲,当前曲目:{self.current_track}") else: print("已经是第一曲") else: print("操作无效") def next_button(self): if self.power and self.cd_loaded: if self.current_track < 5: # 假设最多 5 首曲目 self.current_track += 1 print(f"播放下一曲,当前曲目:{self.current_track}") else: print("已经是最后一曲") else: print("操作无效") # 测试代码 cd_player = CDPlayer() cd_player.power_button() # 打开电源 cd_player.load_button() # 装入 CD cd_player.play_button() # 播放 cd_player.next_button() # 下一曲 cd_player.pause_button() # 暂停 cd_player.previous_button() # 前一曲 cd_player.eject_button() # 弹出 CD cd_player.power_button() # 关闭电源 ``` 在上述代码中,我们创建了一个 `CDPlayer` 类来表示 CD 播放器。通过不同的方法来模拟各个按键的操作,并根据电源状态和 CD 装载状态来控制操作的有效性。你可以根据实际需求对代码进行进一步的扩展和优化。 [2024-08-26 06:31:50 | AI写代码神器 | 639点数解答]