创建型模式 - 简单工厂模式

概述

在简单工厂模式中,可以根据参数的不同返回不同类的实例。简单工厂模式专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类。

优点

客户端无须知道所创建的具体产品类的类名,只需要知道具体产品类所对应的参数即可。

缺点

系统扩展困难,一旦添加新产品就不得不修改工厂逻辑,在产品类型较多时,有可能造成工厂逻辑过于复杂,不利于系统的扩展和维护。

类图

在这里插入图片描述

代码块

#include <iostream>

using namespace std;

class Product
{
public:
	virtual int use() = 0;
protected:
	string m_type;
};

class ProductA : public Product
{
public:
	ProductA(){ m_type = "A"; }
	virtual int use()
	{
		cout << "use in the " << m_type << endl;
		return 0;
	}
};

class ProductB : public Product
{
public:
	ProductB() { m_type = "B"; }
	virtual int use()
	{
		cout << "use in the " << m_type << endl;
		return 0;
	}
};

class Factory
{
public:
	static Product *createProduct(string type)
	{
		if(type == "A")
		{
			return new ProductA();
		}
		else if(type == "B")
		{
			return new ProductB();
		}
		else
		{
			return NULL;
		}
	}
};


int main()
{
	Product *pro = Factory::createProduct("B");
	pro->use();
	delete pro;
	return 0;
}

参考

https://design-patterns.readthedocs.io/zh_CN/latest/creational_patterns/simple_factory.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值