1. 程式人生 > >啃食c++(簡單設計模式)

啃食c++(簡單設計模式)

簡單工廠模式
該設計模式是多型的一種應用例項,簡單工廠模式是有一個生產物件決定生產那一產品,例如接下來的例子中,將friut作為父類,其子類就是各種水果,在這裡就建立了兩個子類引入,然後將各種水果物件作為生產者garden的私有資料成員,通過出生產者來獲取想要的水果型別。

#include<iostream>
using namespace std;
enum{APPLE  = 0 ,GRAPES = 1};
class friut{
public :
    friut(){}
    virtual ~friut(){}
    virtual void plant(){} 
    virtual void grow(){}
    virtual void harvest() {}
};
class apple:public friut{
public:
    apple(){}
    ~apple() {}
    void plant(){
        cout<<"apple has been plant...."<<endl ;
    }
    void grow(){
        cout<<"apple is growing..."<<endl ;
    }
    void harvest(){
        cout<<"apple harvest!"<<endl ;
    }
};
class grapes:public friut{
public :
    grapes() {}
    ~grapes() {}
    void plant(){
        cout<<"grapes has been plant...."<<endl ;
    }
    void grow(){
        cout<<"grapes is growing..."<<endl ;
    }
    void harvest(){
        cout<<"grapes harvest!"<<endl ;
    }
};
//建立生產者的類
class garden{
public:
    garden(){}
    ~garden(){}
    //通過該方法實現不同水果的生產,並將該水果返回
    friut *getFriut(int fr){
        switch(fr){
            case APPLE:
              app = new apple;
                app->plant();
                app->grow();
                app->harvest();
                return app;
            case GRAPES:
                grps=new grapes ;
                grps->plant();
                grps->grow();
                grps->harvest();
                return grps ;
        }
    }
    //生產者當前能生存的水果種類
private:
    apple * app ;
    grapes * grps;
};
int main(){
    
    garden gd ;
    friut* app ;
    friut *grps ;
 //通過父類接收
    app= gd.getFriut(APPLE);
    grps=gd.getFriut(GRAPES);
//記得將申請的資源釋放
    delete app ;
    delete grps;
    app = NULL ;
    grps = NULL;
}

執行截圖:
在這裡插入圖片描述
單例模式
在學習java語言時,對單例模式有一個概念,但是也用java實現了一個簡單的單例模式。單例模式自己對其理解就是,一個類只能產生一個物件,這種設計模式感覺用處挺大的,尤其在以後的面向物件的語言開發中,有寫物件一個程式只能存在一個,這時就可以用這種設計模式來實現此功能。
對於c++單例設計模式,也時大同小異,在這裡我將具體實現描述一下就行,以備以後複習所用。

#include<iostream>
#include<string>
using namespace std;
class single{
private:
    //單例建立一個,static關鍵字意味著這個物件之建立一次,作用域是整個類區
    static single *s ;
    //將單例建構函式設為私有
    single(){}
    ~single(){}
   // single& operator=(const single&){}
public:
//在公有方法區只留一個介面,供使用者獲得此單例,該方法為類方法,通過類名呼叫
    static single* getSingle(){
        if(s == NULL){
            s = new single;
            cout<<"single ton has been ..."<<endl;
        }
        return s ;
    }
    void dosomething(){
        cout<<"singleton singleton"<<endl ;
    }
    void deletemyself(){
        delete s;
        s = NULL;
        cout<<"the singleton has been destroy!"<<endl;
    }
};
//初始化單例指向NULL
single* single::s = NULL ;
int main(){
   
    single::getSingle()->dosomething();
    single::getSingle()->deletemyself();
}

在這裡插入圖片描述
感覺c++建立單例相比於java跟抽象一些,但都不是很難,以上建立單例的方法為c++中的懶漢單例模式,意思是隻有在用時才建立該單例物件。還有一種時餓漢單例模式,即在用之前已經建立好了該單例。
只需上面的程式:在s初始化時直接new該類,外部呼叫get函式直接返回s即可。這就是餓漢模式。
好啦!!!對於c++總結告一段落,又要繼續沉溺在c++中啦~~~