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();
}
相关推荐
感哥10 小时前
C++ 面向对象
c++
晨米酱12 小时前
JavaScript 中"对象即函数"设计模式
前端·设计模式
沐怡旸12 小时前
【底层机制】std::shared_ptr解决的痛点?是什么?如何实现?如何正确用?
c++·面试
数据智能老司机17 小时前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
数据智能老司机18 小时前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机18 小时前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机18 小时前
精通 Python 设计模式——性能模式
python·设计模式·架构
使一颗心免于哀伤18 小时前
《设计模式之禅》笔记摘录 - 21.状态模式
笔记·设计模式
感哥18 小时前
C++ STL 常用算法
c++
saltymilk1 天前
C++ 模板参数推导问题小记(模板类的模板构造函数)
c++·模板元编程