【设计模式】工厂模式
工厂模式解决具有一系列相同属性、方法的类的创建问题。
首先将具有相同属性、方法的类ConcreteProduct抽象出基类Product。
为每个Product创建一个工厂类ConcreteFactory,工厂类又抽象出基类Factory,基类Factory中定义纯虚函数ConcreteFactory。
C++代码实现:
Product.h
#ifndef _Product_H_ #define _Product_H_ #include <iostream> class Product { public: Product(){} virtual ~Product(){} virtual void Do() = 0; protected: private: }; class ConcreteProduct1 : public Product { public: ConcreteProduct1(){} virtual ~ConcreteProduct1(){} virtual void Do(); protected: private: }; class ConcreteProduct2 : public Product { public: ConcreteProduct2(){} virtual ~ConcreteProduct2(){} virtual void Do(); protected: private: }; #endif
Product.cpp
#include "Product.h" void ConcreteProduct1::Do() { std::cout << "Product1 Do!" << std::endl; } void ConcreteProduct2::Do() { std::cout << "Product2 Do!" << std::endl; }
Factory.h
#ifndef _FACTORY_H_ #define _FACTORY_H_ #include "Product.h" class Factory { public: Factory(){} virtual ~Factory(){} virtual Product* CreateProduct() = 0; protected: private: }; class ConcreteFactory1 : public Factory { public: ConcreteFactory1(){} virtual ~ConcreteFactory1(){} virtual Product* CreateProduct(); protected: private: }; class ConcreteFactory2 : public Factory { public: ConcreteFactory2(){} virtual ~ConcreteFactory2(){} virtual Product* CreateProduct(); protected: private: }; #endif
Factory.cpp
#include "Factory.h" Product* ConcreteFactory1::CreateProduct() { return new ConcreteProduct1(); } Product* ConcreteFactory2::CreateProduct() { return new ConcreteProduct2(); }
main.cpp
#include "Factory.h" #include "Factory.h" class Test { public: Test(){} ~Test(){} void DoTest(Factory* f) { Product* p = f->CreateProduct(); p->Do(); } protected: private: }; int main(int argc,char* argv[]) { Test* t = new Test(); Factory* f1 = new ConcreteFactory1(); t->DoTest(f1); Factory* f2 = new ConcreteFactory2(); t->DoTest(f2); return 0; }