設計模式前奏–封裝繼承

設計模式前奏–封裝繼承

既然大家的工作是做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

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