说明:相信大家都知道一个经典的案例.关于电脑对不同的设备进行读取.
1 定义一个基类(移动存储设备类)其中包括两个虚方法
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Computer { public abstract class MobileDevice { public abstract void Read(); public abstract void Write(); } }
MobileDevice
2 定义三个类MP3.U盘
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Computer { public class FleshDisk:MobileDevice { public override void Read() { Console.WriteLine("U-盘,读数据"); } public override void Write() { Console.WriteLine("U-盘,写数据"); } } }
FleshDisk
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Computer { public class MP3 : MobileDevice { public override void Read() { Console.WriteLine("MP3,读数据"); } public override void Write() { Console.WriteLine("MP3,写数据"); } public void Play() { Console.WriteLine("MP3-播放音乐"); } } }
MP3
3 定义一个电脑类
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Computer { public class Computer { public MobileDevice MS { set;get;} public void CPUWrite() { this.MS.Write(); } public void CPUReader() { this.MS.Read(); } } }
Computer
4 接下来在主方法中实现将变得很容易
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Computer { class Program { static void Main(string[] args) { //定义子类 MP3 mp3 = new MP3(); Computer c = new Computer(); c.MS = mp3; c.CPUWrite(); c.CPUReader(); Console.Read(); } } }
Main
5 而且如果突然来了一个手机类,其余代码几乎不用修改
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Computer { public class TPhone:MobileDevice { public override void Read() { Console.WriteLine("手机,读数据"); } public override void Write() { Console.WriteLine("手机,写数据"); } } }
TPhone
只要将Main方法中添加
c.MS = new TPhone();
时间: 2024-10-13 12:22:23