C++设计模式学习笔记03_工厂方法1

0、工厂方法

1、继续前面的总结,前面说到,当工厂需要生产新的产品时,简单工厂模式需要我们对代码进行修改,而且不是代码的扩展,而是代码比较底层的修改了,因此会带来很多后期测试等等的问题,工厂方法模式应运而生
2、工厂方法简单来说就是利用了C++的抽象类(定义了纯虚函数的类),将产品继承在该抽象类下,定义一个抽象类(产品),产品都继承该抽象类,工厂每次根据需要,产生对应的产品
3、工厂也定义一个抽象类,生产不同的产品,则建起不同的工厂
4、在工厂方法的模式下,若是希望引入一种新的产品,只需要定义一个新的类,将该类继承在定义好的产品抽象类下,在建起(引入)新的工厂用来生产新的产品
5、不同产品由不同的工厂生产,在程序看来似乎是有些繁琐,不过代码从逻辑上看起来则很清晰
#include <iostream>
using namespace std;

class Product
{
public:
	virtual void ShowYouself() = 0;
private:

};

class ProtuctA : public Product
{
public:
	void ShowYouself()
	{
		cout << "创建了A" << endl;
	}
private:
};

class ProtuctB : public Product
{
public:
	void ShowYouself()
	{
		cout << "创建了B" << endl;
	}
private:
};
//******************************以下是工厂*****************************
class Fectory
{
public:
	virtual Product *CreateProtect() = 0;
};

class FectoryA : public Fectory
{
public:
	Product *CreateProtect()
	{
		cout << "来到工厂A" << endl;
		return new ProtuctA;
	}
};

class FectoryB : public Fectory
{
public:
	Product *CreateProtect()
	{
		cout << "来到工厂B" << endl;
		return new ProtuctB;
	}
};
//********************************************************
int main(void)
{
	Fectory *fectoryA = new FectoryA();
	Fectory *fectoryB = new FectoryB();

	Product *protectA = fectoryA->CreateProtect();
	Product *protectB = fectoryB->CreateProtect();
	protectA->ShowYouself();
	protectB->ShowYouself();

	if (protectA != NULL)
	{
		cout << "protectA被回收" << endl;
		delete protectA;
		protectA = NULL;
	}
	if (protectB != NULL)
	{
		cout << "protectB被回收" << endl;
		delete protectB;
		protectB = NULL;
	}
	if (fectoryA != NULL)
	{
		cout << "fectoryA被回收" << endl;
		delete fectoryA;
		fectoryA = NULL;
	}
	if (fectoryB != NULL)
	{
		cout << "fectoryB被回收" << endl;
		delete fectoryB;
		fectoryB = NULL;
	}
	system("pause");
	return 0;
}
6、于是乎又出现了一种情况,如果现在希望生产一个新的产品,在工厂方法的模式下,我们需要建立新的产品类,新的工厂类,那么会不会有这么一种情况,新的产品和之前的产品存在着某种关系(比如电脑显示屏和电视显示屏),那么显然我们需要的是让原来生产电脑显示屏的工厂加一条生产电视显示屏的生产线即可,于是抽象工厂类应运而生…

猜你喜欢

转载自blog.csdn.net/weixin_42718004/article/details/84972911