面向对象多态案例

案例:有一台有品牌的电脑他有2个功能开机和关机,它可以插2个USB接口(实现 读,写)。 一个是U盘,一个是硬盘

类图:

 

class Computer
    {
        private string brand;
        public IUsb IUsb_1;
        public IUsb IUsb_2;

        public string Brand
        {
            get { return brand; }
            set { brand = value; }
        }

        public Computer(string brand)
        {
            this.brand = brand;
        }

        public void Start()
        {
            Console.WriteLine("{0}品牌的电脑开机中。。。。",Brand);
        }

        public void End()
        {
            Console.WriteLine("{0}品牌的电脑关机中。。。。", Brand);
        }

    }
Computer
 interface IUsb
    {
        void Read();
        void Write(string content);
    }
IUsb
 class UBase:Computer,IUsb
    {
        private string content;
        public string Content
        {
            get { return content; }
            set { content = value; }
        }

       public UBase(string brand) : base(brand)
        {

        }

        public void Read()
        {
            Console.WriteLine("{0}读取数据{1}",Brand,content);
        }

        public void Write(string content)
        {
            this.content += content ;
            Console.WriteLine("{0}写入数据{1}",Brand,content);
        }

      
    }
UBase
class UzileiA:UBase
    {
        private int content;//存储空间
        public UzileiA(string content) : base(content)
        {

        }
    }
U盘子类
class HardB:UBase
    {
        private int content;//存储空间
        public HardB(string content) : base(content)
        {

        }
    }
Hard子类
  class Program
    {
        static void Main(string[] args)
        {
            UBase uBase1 = new UzileiA("金士顿32G"); //里氏替换   子类可以赋值给父类
            //有一台电脑他有2个接口可以插USB 和 硬盘 
            Computer cp = new Computer("华硕");
            cp.Start();
            cp.IUsb_1 = uBase1;
            cp.IUsb_1.Write("你好。");
            cp.IUsb_1.Read();



            cp.End();
            Console.ReadKey();
        }
    }
调用

 

 

posted @ 2017-07-13 13:16  小林博客  阅读(230)  评论(0编辑  收藏  举报