对于抽象工厂的封装
对于抽象工厂的封装 #ifndef _AbstractFactory_ #define _AbstractFactory_ #include <hash_map> /** *@brief 具体工厂类 *@param Product 抽象产品 *@param ConcreateProduct 具体产品 */ template <typename Product, typename ConcreateProduct> class ConcreateCreator { public: //生产具体产品 static Product* CreateProduct() { return new ConcreateProduct(); } }; /** *@brief */ template <typename Product> class Creator { public: Creator(){} ~Creator(){} private: Creator(Creator&); public: /** *@brief 根据具体产品生成具体工厂,并注册进抽象工厂 *@param ConcreteProduct 具体产品 */ template<typename ConcreteProduct> void RegisterCreator(const int& _type) { m_ConcreteCreators[_type] = ConcreateCreator<Product, ConcreteProduct>::CreateProduct; } /** *@brief 删除所有具体工厂 */ void UnRegisterAllCreators() { m_ConcreteCreators.clear(); } /** *@brief 生产_type类型的产品 */ Product* CreateProduct(const int& _type) { MapRegisterCreatorItem::iterator type = m_ConcreteCreators.find(_type); if (type != m_ConcreteCreators.end()) { CreateProductDelegate create = type->second; if (create != 0) { return create(); } } return nullptr; } private: typedef Product* (*CreateProductDelegate)( ); // 生产产品的函数委托 typedef stdext::hash_map<int, CreateProductDelegate> MapRegisterCreatorItem; MapRegisterCreatorItem m_ConcreteCreators; // 保存所有注册过的具体工厂 }; #endif #ifndef _Packet_ #define _Packet_ #include <iostream> /** *@brief 包类型 */ enum PktType { ePktType_Login, ePktType_Logout, }; /** *@brief 产品抽象类 */ class Packet { public: virtual void Send() = 0; virtual ~Packet() = 0; }; inline Packet::~Packet() { } /** *@LoginPacket 具体产品类 */ class LoginPacket : public Packet { public: void Send() { std::cout << "Send Longin Packet" << std::endl; } }; class LogoutPacket : public Packet { public: void Send() { std::cout << "Send Lonout Packet" << std::endl; } }; #endif #include "AbstractFactory.h" #include "Packet.hpp" int main() { Creator<Packet>* pFactory = new Creator<Packet>;// 创建抽象工厂 pFactory->RegisterCreator<LoginPacket>(ePktType_Login);//创建具体工厂,并注册进抽象工厂 pFactory->RegisterCreator<LogoutPacket>(ePktType_Logout);//创建具体工厂,并注册进抽象工厂 //抽象工厂创建具体产品 Packet* pLoginPkt = pFactory->CreateProduct(ePktType_Login); Packet* pLogoutPkt = pFactory->CreateProduct(ePktType_Logout); pLoginPkt->Send(); pLogoutPkt->Send(); pFactory->UnRegisterAllCreators(); delete pFactory; pFactory = nullptr; getchar(); return 0; }