定義一個簡單工廠類,它能夠根據參數的不一樣返回不一樣類的實例,被建立的實例一般都具備共同的父類。ios
簡單工廠模式有如下的結構:git
SimpleFactory.h函數
#ifndef SIMPLEFACTORY_H #define SIMPLEFACTORY_H #include <iostream> #include <string> //抽象產品類AbstractProduct(並不是真正意義上的抽象類,含有純虛函數纔是抽象類) class AbstractSportProduct { public: AbstractSportProduct(){} ~AbstractSportProduct(){} //虛函數 virtual void printName(){} virtual void play(){} }; //具體產品類Basketball class Basketball :public AbstractSportProduct { public: Basketball(){} ~Basketball(){} //具體實現方法 void printName(); void play(); }; //具體產品類Football class Football :public AbstractSportProduct { public: Football(){} ~Football(){} //具體實現方法 void printName(); void play(); }; //工廠類 class Factory { public: Factory(){} ~Factory(){} AbstractSportProduct *getSportProduct(std::string productName); }; #endif // TSIMPLEFACTORY_H
SimpleFactory.cppcode
#include "SimpleFactory.h" //Basketball方法 void Basketball::printName(){ printf("Basketball\n"); } void Basketball::play(){ printf("play Basketball\n"); } //Football方法 void Football::printName(){ printf("Football\n"); } void Football::play(){ printf("play Football\n"); } //工廠方法 AbstractSportProduct *Factory::getSportProduct(std::string productName) { AbstractSportProduct *pro = NULL; if (productName == "Basketball") { pro = new Basketball(); } else if (productName == "Football") { pro = new Football(); } return pro; }
main.cppblog
#include "SimpleFactory.h" int _tmain(int argc, _TCHAR* argv[]) { Factory *fac = new Factory(); AbstractSportProduct *product = NULL; product = fac->getSportProduct("Basketball"); product->printName(); product->play(); product = fac->getSportProduct("Football"); product->printName(); product->play(); return 0; }
輸出結果:
字符串
優勢:get
缺點:源碼
gitee: https://gitee.com/CogenCG/DesignModestring