Factory Method工廠方法C++版
阿新 • • 發佈:2019-01-01
#pragma once //product.h #ifndef PRODUCT_H #define PRODUCT_H #include <iostream> using namespace std; class Product { public: Product() {} ~Product(){} virtual void name() = 0; }; class Product1:public Product { public: Product1() {} ~Product1(){} void name() { cout << "Product1" << endl; } }; class Product2:public Product { public: Product2() {} ~Product2(){} void name() { cout << "Product2" << endl; } }; #endif // !PRODUCT_H
#pragma once //factory.h #ifndef FACTORY_H #define FACTORY_H #include "product.h" class Factory { public: Factory() {} ~Factory(){} virtual Product* Create() = 0; }; class ConcreteFactory1 :public Factory { public: ConcreteFactory1() {} ~ConcreteFactory1() {} Product*Create() { return new Product1; } }; class ConcreteFactory2 :public Factory { public: ConcreteFactory2() {} ~ConcreteFactory2() {} Product*Create() { return new Product2; } }; #endif // !FACTORY_H
//main.cpp #include <iostream> #include "factory.h" int main() { cout << "生產開始"<< endl; Factory* pFactory1 = new ConcreteFactory1(); Product* pProduct1 = pFactory1->Create(); pProduct1->name(); Factory* pFactory2 = new ConcreteFactory2(); Product* pProduct2 = pFactory2->Create(); pProduct2->name(); delete pFactory1; pFactory1 = NULL; delete pFactory2; pFactory2 = NULL; system("pause"); return 0; }