C++工厂模式

01 工厂模式解决了什么问题

在实际的项目中,如果只是借助关键字new来创建类的实例,在类的种类越来越多的情况下,很难准确的记住他们的名字,这时候可以将相关类的创建封装在一种"工厂类"中。当要创建相关的类的实例的时候,就借助"工厂实例"中的成员函数完成实例的创建。

02 工厂模式的种类

  • 简单工厂模式
    • 这种模式不利于后期更多"产品类的加入",因为在简单工厂模式下,只存在一个工厂类,而得到不同的产品是通过调用工厂类函数的传入参数的时候决定的。如果有新的产品加入,则需要在其函数中进行类似if判断或者switch判断的添加,违反了代码封闭性原则。
  • 工厂方法模式
    • 这种模式是针对不同的产品建立不同的工厂类,这样在调用工厂类成员函数创建产品实例的时候就不用传入参数来确定具体要生产哪一种产品。
  • 抽象工厂模式(没有在代码中列出)
    • 当产品分若干大类的时候,这时候构建生产这些大类的纯虚工厂函数,然后在根据具体需要的产品,构建其派生类,重写工厂抽象基类中的生产函数从而获得需要的产品。

03 Show me the code

#include <iostream>


using namespace std;


// 某一种产品基类
class Product_base {
public:
	virtual ~Product_base() {}

	virtual void name() const = 0;
};


// Product_A
class Product_A: public Product_base {
public:
	void name() const {
		cout << "I'm A." << endl;
	}
};


// Product_B
class Product_B: public Product_base {
public:
	void name() const {
		cout << "I'm B." << endl;
	}
};


// Product_C
class Product_C: public Product_base {
public:
	void name() const {
		cout << "I'm C" << endl;
	}
};


// ========================================
// 简单工厂
class Simple_factory {
public:
	Product_base* make(const string& name) const {
		if (name == "A") {
			return new Product_A();
		} else if (name == "B") {
			return new Product_B();
		} else if (name == "C") {
			return new Product_C();
		} else {
			cout << "没有这种产品" << endl;
			exit(1);
		}
	}
};
// =========================================


// =========================================
// 工厂方法模式,工厂类是一个抽象基类
class Factory_base {
public:
	virtual ~Factory_base() {}

	virtual Product_base* make() const = 0;
};

// 具体生产A的工厂
class Factory_A: public Factory_base {
public:
	Product_base* make() const {
		return new Product_A();
	}
};

// 具体生产B的工厂
class Factory_B: public Factory_base {
public:
	Product_base* make() const {
		return new Product_B();
	}
};

// 具体生产C的工厂
class Factory_C: public Factory_base {
public:
	Product_base* make() const {
		return new Product_C();
	}
};
// =========================================


int main() {
	// 创建一个产品基类的指针
	Product_base* it = nullptr;

	// 简单工厂模式
	it = Simple_factory().make("A");
	it->name();
	delete it;
	it = nullptr;
	
	// 工厂方法模式
	it = Factory_B().make();
	it->name();
	delete it;
	it = nullptr;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值