C++二十三种设计模式之抽象工厂模式

C++二十三种设计模式之抽象工厂模式

一、组成

抽象产品类 :声明产品功能公共接口。
具体产品类 :实现产品功能接口。
抽象工厂类 :声明创建一组具体产品公共接口。
具体工厂类:实现创建一组具体产品接口。

二、特点

1、抽象工厂创建具体产品接口返回抽象产品类型。

2、一个具体工厂创建一组特定风格产品。

三、目的

无需指定具体类的情况下,为一组相互依赖的对象提供创建接口。

四、缺点

1、违反开闭原则,新增产品类需要改动原有的工厂类。

2、场景限制问题,通常用于创建一组相互依赖的对象,意味着不适合于高度灵活的场景。

五、示例代码

javascript 复制代码
#include<iostream>
#include <vector>
#include <string>
#include <mutex>

using namespace std;

class Shape;//抽象产品类
class Rectangle;//具体产品类
class Circle;//具体产品类
class Color;//抽象产品类
class Red;//具体产品类
class Blue;//具体产品类
class AbstractFactory;//抽象工厂类
class ConcreteFactory;//具体工厂类
class ConcreteFactory2;//具体工厂类

class Shape {
public:
	virtual ~Shape() {}
	virtual void draw() = 0;
};

class Rectangle:public Shape {

public:
	~Rectangle() {}
	void draw() {
		cout << "Drawing a Rectangle" << endl;
	}
};

class Circle :public Shape {

public:
	~Circle() {}
	void draw() {
		cout << "Drawing a Circle" << endl;
	}
};

class Color {
public:
	virtual ~Color() {};
	virtual void fill() = 0;
};

class Red : public Color{
public:
	~Red() {}
	void fill() {
		cout << "Filling with Red Color" << endl;
	}
};

class Blue : public Color {
public:
	~Blue() {}
	void fill() {
		cout << "Filling with Blue Color" << endl;
	}
};

class AbstractFactory {
public:
	virtual ~AbstractFactory() {};
	virtual unique_ptr<Shape> createShape() = 0;
	virtual unique_ptr<Color> createColor() = 0;
};

class ConcreteFactory : public AbstractFactory {
public:
	~ConcreteFactory() {};
	unique_ptr<Shape> createShape() {
		return make_unique<Rectangle>();
	};
	unique_ptr<Color> createColor() {
		return make_unique<Red>();
	};
};

class ConcreteFactory2 : public AbstractFactory {
public:
	~ConcreteFactory2() {};
	unique_ptr<Shape> createShape() {
		return make_unique<Circle>();
	};
	unique_ptr<Color> createColor() {
		return make_unique<Blue>();
	};
};

int main() {
	AbstractFactory* factory = new ConcreteFactory();
	unique_ptr<Shape> shape = factory->createShape();
	unique_ptr<Color> color = factory->createColor();
	shape->draw();
	color->fill();

	AbstractFactory* factory2 = new ConcreteFactory();
	unique_ptr<Shape> shape2 = factory->createShape();
	unique_ptr<Color> color2 = factory->createColor();
	shape2->draw();
	color2->fill();
}
相关推荐
咖啡八杯5 小时前
GoF设计模式——备忘录模式
java·后端·spring·设计模式
apocelipes7 小时前
常用编程语言和库的正则表达式性能对比
c语言·c++·python·性能优化·golang·开发工具和环境
槑有老呆9 小时前
从 Prompt Engineering 到 Harness Engineering:AI 编程的下一次跃迁
设计模式
HjhIron17 小时前
从Prompt到Context:大模型应用开发的范式转移
设计模式·aigc·ai编程
郝学胜_神的一滴2 天前
CMake 034:生成器表达式:解耦构建时序、精简分支逻辑的终极利器
c++·cmake
咖啡八杯2 天前
GoF设计模式——中介者模式
java·后端·spring·设计模式
见过夏天2 天前
C++ 基础入门完全指南
c++
胡萝卜术3 天前
从“分数打架”到“排名投票”:为什么你的ChatBI必须用RRF?
算法·设计模式·面试
亦暖筑序4 天前
Java 8老系统Browser Agent实战:三层拦截把AI操作后台变成可审计流程
java·后端·设计模式
用户805533698034 天前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt