首页 > 代码库 > 步步为营-03-一个经典的多态案例

步步为营-03-一个经典的多态案例

说明:相信大家都知道一个经典的案例.关于电脑对不同的设备进行读取.

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();

技术分享

 

步步为营-03-一个经典的多态案例