// 设计模式2-抽象工厂模式.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//https://www.runoob.com/design-pattern/abstract-factory-pattern.html
抽象工厂模式(Abstract Factory Pattern)是围绕一个超级工厂创建其他工厂。该超级工厂又称为其他工厂的工厂。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
在抽象工厂模式中,接口是负责创建一个相关对象的工厂,不需要显式指定它们的类。每个生成的工厂都能按照工厂模式提供对象。
#include <iostream>
#include <string>
struct Shape {
//纯虚函数
virtual void Draw() = 0;
};
//circle
struct Circle :Shape {
//
void Draw() override {
std::cout << "draw circle" << std::endl;
}
};
//rectangle
struct Rectangle :Shape {
//
void Draw() override {
std::cout << "draw rectangle" << std::endl;
}
};
//
struct Color {
//
virtual void Draw() = 0;
};
//
struct Red :Color {
//
void Draw() override {
std::cout << "draw red" << std::endl;
}
};
//
struct Black :Color {
//
void Draw() override {
std::cout << "draw black" << std::endl;
}
};
//抽象工厂类
struct Factory {
virtual Shape* CreateShape(std::string shape) = 0;
virtual Color* CreateColor(std::string color) = 0;
};
//
//
struct ShapeFactory :Factory {
//
Shape* CreateShape(std::string shape) override {
if (shape == "rectangle")
return new Rectangle();
if (shape == "circle")
return new Circle();
}
//
Color* CreateColor(std::string color)override {
return nullptr;
}
};
//
struct ColorFactory :Factory {
//
Shape* CreateShape(std::string shape) override {
return nullptr;
}
//
//
Color* CreateColor(std::string color)override {
if (color == "red")
return new Red();
if (color == "black")
return new Black();
}
};
//
struct FactoryProducer{
//
static Factory* Get(std::string t) {
if (t == "shape")return new ShapeFactory();
if (t == "color") return new ColorFactory();
}
};
int main()
{
//
Factory * shape = FactoryProducer::Get("shape");
shape->CreateShape("rectangle")->Draw();
//
Factory * color = FactoryProducer::Get("color");
color->CreateColor("red")->Draw();
std::cout << "Hello World!\n";
}
//输出
//draw rectangle
//draw red
//Hello World!