設計模式 簡單工廠模式(C )

2021-06-08 01:56:49 字數 2118 閱讀 3079

一.簡單工廠模式又稱靜態工廠方法模式(static factory method),它不是gof 所講的23種設計模式之一,但是它卻是我們在編碼過程中經常使用的方法之一。

1.靜態工廠方法統一管理物件的建立。

靜態工廠方法通過傳入的引數判斷決定建立哪乙個產品的例項,封裝了物件的建立,客戶端只管消費,實現了對責任(模組)的分割。

2.靜態工廠方法推遲了產品的例項化。

通過xml配置檔案就能改變具體要建立的產品例項,修改為其它的產品例項,**不須重新編譯。

classfile.h

#pragma once

class basicobject

;class addobject : public basicobject

; ~addobject(void){};

virtual int operation_function(int a,int b);

};class subobject : public basicobject

; ~subobject(void){};

virtual int operation_function(int a,int b);

};class mulobject : public basicobject

; ~mulobject(){};

virtual int operation_function(int a,int b);

};class divobject : public basicobject

; ~divobject(){};

virtual int operation_function(int a,int b);

};class tochobject : public basicobject

; ~tochobject(){};

virtual int operation_function(int a,int b);

};class arithoperato***ctory

; ~arithoperato***ctory(){};

basicobject* createarithoperator(const char chsrc);

};

classfile.cpp

#include "stdafx.h"

#include "classfile.h"

basicobject::basicobject(void) :

tempa(0),

tempb(0)

basicobject::~basicobject(void)

int basicobject::operation_function(int a,int b)

int addobject::operation_function(int a,int b)

int subobject::operation_function(int a,int b)

int mulobject::operation_function(int a,int b)

int divobject::operation_function(int a,int b)

int tochobject::operation_function(int a,int b)

basicobject * arithoperato***ctory::createarithoperator(const char chsrc)

return obj;

}

main.cpp

#include "classfile.h"

#include #include using namespace std;

int _tmain(int argc, _tchar* argv)

int k = addobj->operation_function(20, 30);

cout << "k = " << k << endl;

system("pause");

return 0;

}

C 設計模式 簡單工廠模式

從設計模式的型別上來說,簡單工廠模式是屬於建立型模式,又叫做靜態工廠方法 static factory method 模式,但不屬於23種 gof設計模式之一。簡單工廠模式是由乙個工廠物件決定建立出哪一種產品類的例項。簡單工廠模式是工廠模式家族中最簡單實用的模式,可以理解為是不同工廠模式的乙個特殊實...

C 設計模式 簡單工廠模式

問題描述 之前在公司做了乙個windows 8平台的閱讀器。首先,需要將電子書中的內容渲染到螢幕上,而電子書每一頁都包含各種各樣的內容,比如 圖形 影象和文字等等 不同的內容,就是不同的物件 在將不同的內容渲染到螢幕上之前,就需要new操作,建立不同的物件,然後再在螢幕上進行描繪。這個時候,就需要進...

C 設計模式 簡單工廠模式

問題描述 之前在公司做了乙個windows 8平台的閱讀器。首先,需要將電子書中的內容渲染到螢幕上,而電子書每一頁都包含各種各樣的內容,比如 圖形 影象和文字等等 不同的內容,就是不同的物件 在將不同的內容渲染到螢幕上之前,就需要new操作,建立不同的物件,然後再在螢幕上進行描繪。這個時候,就需要進...