课程作业七

作业要求

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

(在车上用手机打的目前的版本可能有排版、代码错误等等
(2017/06/09 22:17更新 果然很炸
(2017/06/11 18:53更新 引入C++17 variant

作业要求

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

关于简单工厂模式

简单工厂模式利用“工厂”,即类RandomFactory接收参数 以此产生类Random的相应子类。其统一了接口,但是扩充子类时修改量繁多。

简单实现

// 需要C++17标准
#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

class Random
{
    public:
    Random(){}
    virtual ~Random(){}
    virtual variant print() { return variant(); }
};

class RandomNum:public Random
{
protected:
    int num;
public:
    RandomNum(){}
    RandomNum(int n):num(n){}
    ~RandomNum(){}
    virtual variant print() 
    {
        variant  numVariant;
        numVariant = num;
        return numVariant;
    }
};


class RandomOperation:public Random
{
protected:
    char symbol;
public:
    RandomOperation(){}
    RandomOperation(char sym):symbol(sym){}
    ~RandomOperation(){}
    virtual variant print()
    {
        variant  symVariant;
        symVariant = symbol;
        return symVariant;
    }
};
    


class RandomFactory{
private:
    int newNum(int RandMin, int RandMax)
    {
        int x;
        x = (static_cast (rand()));

        if (x != 0)
           x = x % (RandMax + 1 - RandMin);
        return (x + RandMin);
    }
public:
    RandomFactory(){}
    ~RandomFactory(){}
    Random* randomClass(const string &mode)
    {
        if (mode=="RandomNum")
        {
            int num=newNum(0,10);
            return (new RandomNum(num));
        }
        else if (mode=="RandomOperation")
        {
            int num=newNum(1,4);
            char c;
            switch (num)
            {
            case 1:c='+';break;
            case 2:c='-';break;
            case 3:c='*';break;
            case 4:c='/';break;
            }
            return (new RandomOperation(c));
        }
        else throw invalid_argument("The argument is invalid.");
    }
};


int main()
{
    srand((unsigned(time(nullptr))));

    RandomFactory ran;

    Random *RanNum=ran.randomClass("RandomNum");
    cout << get((*RanNum).print());
    Random *RanOper = ran.randomClass("RandomOperation");
    cout << get((*RanOper).print());

    delete RanNum;
    delete RanOper;
    RanNum = ran.randomClass("RandomNum");
    cout << get((*RanNum).print());
    RanOper = ran.randomClass("RandomOperation");
    cout << get((*RanOper).print());

    delete RanNum;
    delete RanOper;
    RanNum = ran.randomClass("RandomNum");
    cout << get((*RanNum).print());
    RanOper = ran.randomClass("RandomOperation");
    cout << get((*RanOper).print());
    return 0;
}

转载于:https://www.cnblogs.com/circlek/p/6973922.html

你可能感兴趣的:(课程作业七)