本文主要是介绍设计模式初探4——抽象工厂(Abstract Factory),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
抽象工厂:为一个产品家族提供了统一的创建接口。当需要这个产品家族的某一系列的时候,可以从抽象工厂中选出相对系的系列来创建一个具体的工厂类别。
适用性:
一个系统要独立于它的产品的创建、组合和表示时。
一个系统要由多个产品系列中的一个来配置时。
当你要强调一系列相关的产品对象的设计以便进行联合使用时。
当你提供一个产品类库,而只想显示它们的接口而不是实现时。
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)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!