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

Posted 逍遥小天狼

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了步步为营-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-一个经典的多态案例的主要内容,如果未能解决你的问题,请参考以下文章

python3操作MongoDB的crud以及聚合案例,代码可直接运行(python经典编程案例)

我是这样一步步理解--主题模型(Topic Model)LDA(案例代码)

读重构一书的收获

Java 多态 ——一个案例 彻底搞懂它

java基础---25. 接口多态综合案例

我是这样一步步理解--主题模型(Topic Model)、LDA(案例代码)