标签:
抽象工厂模式(AbstructFactory)
优点:
1.可以支持不同类型的产品,使得产品的灵活性更强
2.可以很方便的一族中间的不同类型的产品
缺点:
结构过于臃肿,如果产品类型过大,就会难以管理
代码实现:
AbstructFactory.h
#ifndef ABSTRUCTFACTORY_H #define ABSTRUCTFACTORY_H /*ProductA*/ class AbstructProductBaseA { public: AbstructProductBaseA(){} ~AbstructProductBaseA(){} virtual void show(); }; class ProductA : public AbstructProductBaseA { public: ProductA(){} ~ProductA(){} void show(); }; class ProductB : public AbstructProductBaseA { public: ProductB(){} ~ProductB(){} void show(); }; /*ProductAA*/ class AbstructProductBaseAA { public: AbstructProductBaseAA(){} ~AbstructProductBaseAA(){} virtual void show(); }; class ProductAA : public AbstructProductBaseAA { public: ProductAA(){} ~ProductAA(){} void show(); }; class ProductBB : public AbstructProductBaseAA { public: ProductBB(){} ~ProductBB(){} void show(); }; /*Factory*/ class AbstructFactory { public: AbstructFactory(){} ~AbstructFactory(){} virtual AbstructProductBaseA *createProductA() = 0; virtual AbstructProductBaseAA *createProductAA() = 0; }; class FactoryA : public AbstructFactory { public: FactoryA(){} ~FactoryA(){} AbstructProductBaseA *createProductA(); AbstructProductBaseAA *createProductAA(); }; class FactoryB : public AbstructFactory { public: FactoryB(){} ~FactoryB(){} AbstructProductBaseA *createProductA(); AbstructProductBaseAA *createProductAA(); }; #endif // ABSTRUCTFACTORY_H
AbstructFactory.cpp
#include "abstructfactory.h" #include <iostream> void AbstructProductBaseA::show() { std::cout << "this is AbstructProductBaseA" << std::endl; } void ProductA::show() { std::cout << "this is ProductA" << std::endl; } void ProductB::show() { std::cout << "this is ProductB" << std::endl; } void AbstructProductBaseAA::show() { std::cout << "this is AbstructProductBaseAA" << std::endl; } void ProductAA::show() { std::cout << "this is ProductAA" << std::endl; } void ProductBB::show() { std::cout << "this is ProductBB" << std::endl; } AbstructProductBaseA *FactoryA::createProductA() { return new ProductA; } AbstructProductBaseAA *FactoryA::createProductAA() { return new ProductAA; } AbstructProductBaseA *FactoryB::createProductA() { return new ProductB; } AbstructProductBaseAA *FactoryB::createProductAA() { return new ProductBB; }
main.cpp
#include <iostream> #include "abstructfactory.h" int main() { AbstructFactory *factory = new FactoryA; factory->createProductA()->show(); factory->createProductAA()->show(); factory = new FactoryB; factory->createProductA()->show(); factory->createProductAA()->show(); return 0; }
标签:
原文地址:http://blog.csdn.net/fu1201520/article/details/51330403