c++設計模式之工廠模式入門篇

  • 設計模式簡介
      設計模式爲開發人員提供一種使用專家設計經驗的有效途徑。設計模式中運用了面向對象編程語言的重要特徵:封裝、繼承、多態等。
      常見的設計模式主要有:工廠模式、策略模式、適配器模式、單例模式、原型模式、模板方法模式、建造者模式、外觀模式、組合模式、代理模式、享元模式、橋接模式、修飾模式、備忘錄模式、中介者模式、職責鏈模式、觀察者模式、狀態模式。
      下面我們來粗略的介紹下C++設計模式之工廠模式
  • 工廠模式
      工廠模式是指:定義一個接口來創建一個對象,但是由子類來決定要實例化哪一個對象。下面我從摘抄的例子來引入:
//首先定義產品類及其子類
class VideoWiring
{
public:
    virtual string PlayVideo()=0;
}

class VCD: public VideoWiring  
{
public:
    string PlayVideo()
    {
        return "正在播放播放VCD";
    }
}
class DVD: public VideoWiring  
{
public:
    string PlayVideo()
    {
        return "正在播放播放DVD";
    }
}
//簡單工廠
class Create
{
public:
    static VideoWiring* factory(string  VideoName)
    {
        switch(VideoName)
        {
            case "DVD":
                return new DVD();
            case "VCD":
                return new VCD();
        }
        return null;
    }
}

client端代碼:
void PlayVideo()
{
     VideoWiring *vw=Create.factory("DVD");
     vw->PlayVideo();
     delete vw;
     
     vw=Create.factory("VCD");
     vw->PlayVideo();
     delete vw;
}

  其利用了多態性不管什麼具體產品都返回一個抽象;利用分裝性,內部產品發生變化時外部使用者不會受到影響;但是上述如果增加了新的產品則不利於開閉原則(對擴展開放,對更改封閉)

//工廠方法:
class Create
{
public:
    virtual VideoWiring* factory()=0;
}

class DVDCreate: public Create
{
    VideoWiring* factory()
    {
        return new DVD();
    }
}

class VCDCreate: public Create
{
    VideoWiring* factory()
    {
        return new VCD();
    }
}
client端代碼:
void PlayVideo()
{
     VideoWiring *dvd,*vcd;
     Create *dvdCreate,*vcdCreate;
    
     dvdCreate=new DVDCreate();
     dvd=dvdCreate->factory();
     dvd->PlayVideo();
     delete dvd;
    
     vcdCreate=new VCDCreate();
     vcd=vcdCreate->factory();
     vcd->PlayVideo();
     delete vcd;
}

  綜上所述:工廠模式是一種定義一個接口來創建一個對象,但是由子類來決定要實例化哪一個對象。將實際創建工作延遲到子類中,滿足面向對象設計的開閉原則(對擴展開放,對更改封閉)。

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