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();
}
相关推荐
端平入洛13 小时前
auto有时不auto
c++
哇哈哈20211 天前
信号量和信号
linux·c++
多恩Stone1 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马1 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
超级大福宝1 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
weiabc2 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法
问好眼2 天前
《算法竞赛进阶指南》0x01 位运算-3.64位整数乘法
c++·算法·位运算·信息学奥赛
yyjtx2 天前
DHU上机打卡D31
开发语言·c++·算法
czxyvX2 天前
020-C++之unordered容器
数据结构·c++
会编程的土豆2 天前
2.25 做题
数据结构·c++·算法