标签:添加 hone cti 子类 new 实现 splay height sys
说明:相信大家都知道一个经典的案例.关于电脑对不同的设备进行读取.
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(); } }
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-盘,写数据"); } } }
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-播放音乐"); } } }
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(); } } }
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(); } } }
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("手机,写数据");
}
}
}
只要将Main方法中添加
c.MS = new TPhone();
标签:添加 hone cti 子类 new 实现 splay height sys
原文地址:http://www.cnblogs.com/YK2012/p/6701141.html