抽象工厂模式(Abstract Factory Pattern)是围绕一个超级工厂创建其他工厂。该超级工厂又称为其他工厂的工厂。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
在抽象工厂模式中,接口是负责创建一个相关对象的工厂,不需要显式指定它们的类。每个生成的工厂都能按照工厂模式提供对象。
意图:提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。
主要解决:主要解决接口选择的问题。
何时使用:系统的产品有多于一个的产品族,而系统只消费其中某一族的产品。
如何解决:在一个产品族里面,定义多个产品。
关键代码:在一个工厂里聚合多个同类产品。
模型仅供参考
ShapeFactory.h
#pragma once
#include<iostream>
/*
Factory Pattern
*/
class Shape
{
public:
virtual void Draw() = 0;
};
class Circle:public Shape
{
public:
virtual void Draw()
{
std::cout << "Draw Circle" << std::endl;
}
};
class Rectangle :public Shape
{
public:
virtual void Draw()
{
std::cout << "Draw Rectangle" << std::endl;
}
};
ColorFactory.h
#pragma once
#include<iostream>
class Color
{
public:
virtual void SetColor() = 0;
};
class BlackColor :public Color
{
virtual void SetColor()
{
std::cout << "Set Color Black" << std::endl;
}
};
class RadColor :public Color
{
virtual void SetColor()
{
std::cout << "Set Color Red" << std::endl;
}
};
AbstractFactoryPattern.h
#pragma once
#include<iostream>
#include "ShapFactory.h"
#include "ColorFactory.h"
class AbstractFactory
{
public:
virtual Shape* CreatShapeObject(std::string ShapeName) = 0;
virtual Color* CreatColorObject(std::string ColorName) = 0;
};
class ShapeFactory:public AbstractFactory
{
public:
Shape* CreatShapeObject(std::string Name)
{
if (Name == "Circle")
{
return new Circle();
}
else if (Name == "Rectangle")
{
return new Rectangle();
}
else
{
std::cout << "Error no match shape Name" << std::endl;
return nullptr;
}
}
Color* CreatColorObject(std::string ColorName)
{
return nullptr;
}
};
class ColorFactory :public AbstractFactory
{
public:
Color* CreatColorObject(std::string Name)
{
if (Name == "Black")
{
return new BlackColor();
}
else if (Name == "Red")
{
return new RadColor();
}
else
{
std::cout << "Error no match shape Name" << std::endl;
return nullptr;
}
}
Shape* CreatShapeObject(std::string Name)
{
return nullptr;
}
};
class FactoryProducer
{
public:
AbstractFactory* GetFactory(std::string Name)
{
if (Name == "Shape")
{
return new ShapeFactory();
}
else if (Name == "Color")
{
return new ColorFactory();
}
else
{
return nullptr;
}
}
};
main.cpp
#include<iostream>
#include "AbstractFactoryPattern.h"
#include "ShapFactory.h"
#include "ColorFactory.h"
void TestAbstractFactoryPattern()
{
FactoryProducer *mBaseFactory = new FactoryProducer();
std::cout << "#### Creat Shape Factory ####" << std::endl;
AbstractFactory *mAbstractFactory = mBaseFactory->GetFactory("Shape");
Shape *BaseShape = mAbstractFactory->CreatShapeObject("Circle");
BaseShape->Draw();
BaseShape = mAbstractFactory->CreatShapeObject("Rectangle");
BaseShape->Draw();
std::cout << "#### Creat Color Factory ####" << std::endl;
mAbstractFactory = mBaseFactory->GetFactory("Color");
Color *BaseColor = mAbstractFactory->CreatColorObject("Black");
BaseColor->SetColor();
BaseColor = mAbstractFactory->CreatColorObject("Red");
BaseColor->SetColor();
}
int main(int argc, char* argv[])
{
TestAbstractFactoryPattern();
return 0;
}
结果展示