设计模式前奏–封装继承

设计模式前奏–封装继承

既然大家的工作是做IT,那我就拿最熟悉的办公用品来做示例。

UML

面向对象三大特性封装、继承、多态。

封装
PC,Dell,IBM这三个类就是封装

继承
Dell:PC,IBM:PC这二处地方用到继承

多态
public virtual string Name{}
public abstract void Describe
这里属性和方法的定义方式就是多态,这篇文章我并没有讲解多态,只是留有接口。

个人电脑基类

abstract class PC   //抽象类
{
    private string name;//私有成员

    public PC(string name)//构造函数
    {
        this.name = name;
    }

    public virtual string Name//属性
    {
        get
        {
            return name;
        }

        set
        {
            name = value;
        }
    }

    public abstract void Describe();//抽象方法
}

Dell电脑具体类

class Dell : PC     //Dell继承抽象类PC
{
    public Dell(string name) : base(name)//传递名称
    {

    }

    public override void Describe()//实现抽象方法
    {
        System.Console.WriteLine("I am {0} personal computer", Name);
    }
}

IBM电脑具体类

class IBM : PC      //IBM继承抽象类PC
{
    public IBM(string name) : base(name)
    {

    }

    public override void Describe()
    {
        System.Console.WriteLine("I am {0} personal computer", Name);
    }
}

调用方式

class Program
{
    static void Main(string[] args)
    {
        System.Console.WriteLine("普通方式 \n");

        PC dell = new Dell("Dell");//创建Dell对象
        //Dell dell = new Dell("Dell");
        dell.Describe();
        dell.Name = "OtherDell";//通过属性赋值
        dell.Describe();

        PC ibm = new IBM("IBM");//创建IBM对象
        //IBM ibm = new IBM("IBM");
        ibm.Describe();
        ibm.Name = "OtherIBM";
        ibm.Describe();
    }
}

PC dell = new Dell(“”);//表示定义一个PC类型的对象dell, 同时创建Dell对象,并把这个创建的对象new Dell(“”)赋值给PC的对象dell,是不是感觉有点绕。
Dell dell = new Dell(“”);//表示定义一个Dell类型的对象dell, 同时创建Dell对象,并把这个创建的对象new Dell(“”)赋值给Dell的对象dell。之所以用这种方式来表述,是因为我是以为上面的代码来说明问题。

这样吧我换下对象名称,这下应该容易理解
PC p = new Dell(“”);//表示定义一个PC对象p, 同时创建Dell对象,并把这个创建的对象赋值给p。
Dell d = new Dell(“”);//表示定义一个Dell对象d, 同时创建Dell对象,并把这个创建的对象赋值给d。

//本来调用代码是以下方式,又怕有的初学者不能理解,所以又重新写了调用方式。
PC pc;
pc = new Dell(“Dell”);
pc.Describe();
pc.Name = “OtherDell”;
pc.Describe();

System.Console.WriteLine();

pc = new IBM(“IBM”);
pc.Describe();
pc.Name = “OtherIBM”;
pc.Describe();

PC dell = new Dell(“Dell”); //面向接口编程
Dell dell = new Dell(“Dell”); //面向细节编程

PC ibm = new IBM(“IBM”);
IBM ibm = new IBM(“IBM”);

好了费话就不多说了,如果你还不明白这二种调用方式的区别,那么你应该去看看C#的基础知实,因为接下来的文章我就不再过多讲解这些基础理论。

track http://blog.csdn.net/cadenzasolo/article/details/50538331

版权所有,转载请注明文章出处 http://blog/csdn.net/cadenzasolo

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章