工廠模式屬於創建型模式,大致可以分爲三類,簡單工廠模式、工廠方法模式、抽象工廠模式。聽上去差不多,都是工廠模式。下面一個個介紹,首先介紹簡單工廠模式,它的主要特點是需要在工廠類中做判斷,從而創造相應的產品。當增加新的產品時,就需要修改工廠類。有點抽象,舉個例子就明白了。有一家生產處理器核的廠家,它只有一個工廠,能夠生產兩種型號的處理器核。客戶需要什麼樣的處理器核,一定要顯示地告訴生產工廠。下面給出一種實現方案。
1、
#ifndef _PATTERNFACTORYMETHOF_H_
#define _PATTERNFACTORYMETHOF_H_
#include <string>
#include <iostream>
#include <vector>
using namespace std;
class Product
{
public :
virtual void use()=0;
};
class Factory
{
public :
virtual Product* createProduct(const string s)=0;
};
class IDCard:public Product
{
private :
string s;
public :
IDCard(const string s)
{
this->s=s;
cout<<s<<endl;
}
virtual void use()
{
cout<<"IDCard--use-->"<<s<<endl;
}
};
class IDCardFactory:public Factory
{
public :
virtual Product* createProduct(const string s)
{
Product *p=new IDCard(s);
return p;
}
};
#endif
2、
#include <iostream>
#include "PatternFactoryMethod.h"
#include <string>
using namespace std;
int main()
{
string s("zhongguorenmin");
Factory *f=new IDCardFactory();
Product *p=f->createProduct(s);
p->use();
system("pause");
return 0;
}