抽象工厂:为一个产品家族提供了统一的创建接口。当需要这个产品家族的某一系列的时候,可以从抽象工厂中选出相对系的系列来创建一个具体的工厂类别。
适用性:
一个系统要独立于它的产品的创建、组合和表示时。
一个系统要由多个产品系列中的一个来配置时。
当你要强调一系列相关的产品对象的设计以便进行联合使用时。
当你提供一个产品类库,而只想显示它们的接口而不是实现时。
UML图:
依然写个小Demo吧:
#include <stdlib.h> #include <iostream> #include <string> using namespace std; class Product { public: virtual generateContent() = 0; void displayMyself() { productContent = generateContent(); cout << productContent << "\n"; } private: string productContent; }; class Shoes : public Product { public: string generateContent(){ return "Shoes has been Created !"; } }; class Clothes : public Product { public: string generateContent(){ return "Clothes has been Created !"; } }; class AbstractFactory { public: virtual Product* createProduct() = 0 }; class ShoesFactory { public: Product* createProduct(){ return new Shoes(); } } class ClothesFactory { public: Product* createProduct(){ return new Clothes(); } } int main(int argc, char* argv[]) { AbstractFactory *factory = new ShoesFactory(); factory->createProduct()->displayMyself(); factory = new ClothesFactory(); factory->createProduct()->displayMyself(); system("pause"); return 0; };
设计模式初探4——抽象工厂(Abstract Factory)
原文地址:http://blog.csdn.net/cloud_castle/article/details/40859345