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();
}
相关推荐
樱木Plus2 天前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
willow2 天前
Axios由浅入深
设计模式·axios
blasit4 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
七月丶4 天前
别再手动凑 PR 了:这个 AI Skill 会按仓库习惯自动建分支、拆提交、提 PR
人工智能·设计模式·程序员
刀法如飞4 天前
从程序员到架构师:6大编程范式全解析与实践对比
设计模式·系统架构·编程范式
九狼4 天前
Flutter + Riverpod +MVI 架构下的现代状态管理
设计模式
静水流深_沧海一粟5 天前
04 | 别再写几十个参数的构造函数了——建造者模式
设计模式
StarkCoder5 天前
从UIKit到SwiftUI的迁移感悟:数据驱动的革命
设计模式
肆忆_5 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++