C#声明一个接口IPlayer,包含5个接口方法:播放、停止、暂停、上一首和下一首
声明一个接口IPlayer,包含5个接口方法:播放、停止、暂停、上一首和下一首。设计一个Windows应用程序,在该程序中定义一个MP3播放器类和一个AVI播放器类,以实现该接口,最后创建相应类的实例测试程序,图
所示为单击“MP3”按钮后,再点击“播放”按钮的效果。如果点击“AVI”按钮后,再点击“播放”按钮,则应显示“正在播放AVI视频!”。
代码如下:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Text5 { public partial class Form3 : Form { IPlayer iplayer; MP3 mp3; AVI avi; public Form3() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { mp3 = new MP3(); iplayer = (IPlayer)mp3; } private void button7_Click(object sender, EventArgs e) { avi = new AVI(); iplayer = (IPlayer)avi; } private void button2_Click(object sender, EventArgs e) { lblshow.Text = iplayer.Pre(); } private void button3_Click(object sender, EventArgs e) { lblshow.Text = iplayer.Stop (); } private void button4_Click(object sender, EventArgs e) { lblshow.Text = iplayer.Play(); } private void button5_Click(object sender, EventArgs e) { lblshow.Text = iplayer.Pause(); } private void button6_Click(object sender, EventArgs e) { lblshow.Text = iplayer.Next(); } } interface IPlayer { string Play(); string Stop(); string Pause(); string Pre(); string Next(); } public class MP3 : IPlayer { //copy from iotword.com public string Play() { return "正在播放MP3歌曲!"; } public string Stop() { return "停止播放MP3歌曲!"; } public string Pause() { return "暂停播放MP3歌曲!"; } public string Pre() { return "播放上一首MP3歌曲!"; } public string Next() { return "播放下一首MP3歌曲!"; } } public class AVI : IPlayer { public string Play() { return "正在播放AVI视频!"; } public string Stop() { return "停止播放AVI视频!"; } public string Pause() { return "暂停播放AVI视频!"; } public string Pre() { return "播放上一个AVI视频!"; } public string Next() { return "播放下一个AVI视频!"; } } }