标签:
用多态模拟,将移动硬盘,U盘,MP3插到电脑上进行读写数据
父类:用抽象类,因为不知道是什么样的移动设备插到电脑上,也不清楚怎样读写
abstract class MobileStorage { public abstract void Read(); public abstract void Write(); }
移动硬盘类:
class MobileDisk : MobileStorage { public override void Read() { Console.WriteLine("移动硬盘在读取数据"); } public override void Write() { Console.WriteLine("移动硬盘在写入数据"); } }
U盘类:
class UDisk : MobileStorage { public override void Read() { Console.WriteLine("U盘在读取数据"); } public override void Write() { Console.WriteLine("U盘在写入数据"); } }
MP3类:
class MP3 : MobileStorage { public override void Read() { Console.WriteLine("MP3在读取数据"); } public override void Write() { Console.WriteLine("MP3在写入数据"); } public void PlayMusic() { Console.WriteLine("MP3在播放音乐"); } }
Computer类:
class Computer { //通过定义字段获得父类 private MobileStorage _ms; public MobileStorage Ms { get { return _ms; } set { _ms = value; } } public void CpuRead() { Ms.Read(); } public void CpuWrite() { Ms.Write(); } //通过传参获得父类 //public void CpuRead(MobileStorage ms) //{ // ms.Read(); //} //public void CpuWrite(MobileStorage ms) //{ // ms.Write(); //} }
Main:
static void Main(string[] args) { //用多态模拟,将移动硬盘,U盘,MP3插到电脑上进行读写数据 //MobileDisk md = new MobileDisk(); //UDisk u = new UDisk(); //MP3 mp3 = new MP3(); //Computer cpu = new Computer(); //cpu.CpuRead(u); //cpu.CpuWrite(u); MobileStorage ms = new MobileDisk();//new UDisk();//new MP3(); Computer cpu = new Computer(); cpu.Ms = ms; cpu.CpuRead(); cpu.CpuWrite(); //cpu.CpuRead(ms); //cpu.CpuWrite(ms); Console.ReadKey(); }
标签:
原文地址:http://www.cnblogs.com/mikie/p/4603481.html