// 设计模式1工厂模式.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//https://www.runoob.com/design-pattern/factory-pattern.html
//在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。
#include <iostream>
#include <string>
class CFactory {
public:
virtual void draw() = 0;
};
//Circle
class Circle : public CFactory{
public:
void draw() override {
std::cout << "circle" << std::endl;
}
};
//Rectangle
class CRectangle :public CFactory {
//
void draw() override {
std::cout << "renctangle" << std::endl;
}
};
//
struct Shape {
static CFactory* Get(std::string shape) {
if (shape == "circle") {
return new Circle();
}
//
if (shape == "rectangle") {
return new CRectangle();
}
}
};
int main()
{
Shape::Get("circle")->draw();
Shape::Get("rectangle")->draw();
std::cout << "Hello World!\n";
}
//输出
//circle
//renctangle
//Hello World!