以下代码来源: 设计模式精解-GoF 23种设计模式解析附C++实现源码
//Product.h
#pragma once class Product { public: virtual ~Product() = 0; protected: Product(); private: }; class ConcreateProduct:public Product { public: ConcreateProduct(); ~ConcreateProduct(); private: protected: };
//Product.cpp
#include"Product.h" #include<iostream> Product::Product() { } Product::~Product() { } ConcreateProduct::ConcreateProduct() { std::cout << "ConcreateProduct" << std::endl; } ConcreateProduct::~ConcreateProduct() { }
//Factory.h
#pragma once class Product; class Factory { public: virtual ~Factory() = 0; virtual Product* CreateProduct() = 0; protected: Factory(); private: }; class ConcreateFactory:public Factory { public: ConcreateFactory(); ~ConcreateFactory(); Product* CreateProduct(); protected: private: };
//Factory.cpp
#include"Factory.h" #include"Product.h" #include<iostream> Factory::Factory(){} Factory::~Factory(){} ConcreateFactory::ConcreateFactory() { std::cout << "ConcreateFactory" << std::endl; } ConcreateFactory::~ConcreateFactory(){} Product* ConcreateFactory::CreateProduct() { return new ConcreateProduct(); }
//main.cpp
#include"Factory.h" #include"Product.h" #include<iostream> int main(int args, char* argv[]) { Factory* fac = new ConcreateFactory();//将类的具体化延迟到了子类。 Product* pro = fac->CreateProduct();//将类中的对象进行了封装。 Product* pro1 = fac->CreateProduct(); return 0; }