课程作业七

课程作业七

题目描述

  • 请将随机生成数字、表达式的部分设计成:一个Random基类,基类中有random()方法。并由该基类派生出RandomNumber类、RandomOperation类,继承并覆盖父类方法。
  • 学习简单工厂模式,思考能否将该模式运用到题目的第一点要求中。

对简单工厂模式的学习

GIT链接

学习博客链接

简单工厂模式又称静态工厂方法模式(Static Factory Method),它不是Gof 所讲的23种设计模式之一,但是它却是我们在编码过程中经常使用的方法之一。

  1. 静态工厂方法通过传入的参数判断决定创建哪一个产品的实例,封装了对象的创建,客户端只管消费,实现了对责任(模块)的分割。
  2. 通过XML配置文件就能改变具体要创建的产品实例,修改为其它的产品实例,代码不须重新编译。

代码展示

class Random                       //基类
{
public:
	Random(){}
	~Random(){}
	virtual char randomOperation() = 0;
	virtual int randomNunber() = 0;
};
class Randomnumber : public Random
{
public:
	Randomnumber(){}
	~Randomnumber(){}
	virtual int randomNunber();                                                        //产生随机数  
	virtual char randomOperation();
};
class Randomoperator :public Random
{
public:
	Randomoperator(){}
	~Randomoperator(){}
	virtual char randomOperation();                                                    //随机符号
	virtual int randomNunber();
};
class Randomfactory
{
public:
	Randomfactory(){}
	~Randomfactory(){}
	static Random *creatrandom(const int & temp);
};
Random * Randomfactory::creatrandom(const int & temp)                                      //实现简单工厂的函数
{
	if (temp == 1)
	{
		return new Randomoperator();
	}
	if (temp == 0)
	{
		return new Randomoperator();
	}
	else
	{
		assert(false);
	}
	return NULL;
}
/*以下为代码片段*/
        int num1, num2, change, count;
	char symbol;
	string str_num1, str_num2, Equation, t;
	Random *temp = NULL;
	temp = Randomfactory::creatrandom(1);
	num1 = temp->randomNunber();
	num2 = temp->randomNunber();
	count = random() % 6 + 2;
	temp = Randomfactory::creatrandom(0);
	symbol = temp->randomOperation();

学习心得和遇到的问题

简单工厂通过传入参数来判断生产哪个类的对象,很像工厂生产产品一样,博客中使用的生产手机例子让我很好的理解了简单工厂的含义。其中用到了纯虚函数,而在纯虚函数的使用上我遇见了很多的问题。比如
对纯虚函数的声明: virtual void funtion1()=0; 纯虚函数一定没有定义,纯虚函数用来规范派生类的行为,即接口。包含纯虚函数的类是抽象类,抽象类不能定义实例,要在定义了其中的纯虚函数之后才可以实例化对象。学习博客链接。通过博客作业,总能学到超前于课堂的知识,让我带着问题去听课,提高自己的编码能力。

原文地址:https://www.cnblogs.com/031602523liu/p/6950600.html