KnightOnHorse的博客

追求技术的道路永无止境

Creational.SimpleFactory简单工厂模式:提供操作符返回运算对象

//提供一个创建对象实例的功能,而无须关心其具体实现



//声明文件

//运算类(其它的加减乘法类从这里继承)
class CAbsOpt{
protected:
    double dNumber1;
    double dNumber2;
public:
    void SetNumber1(double number);
    double GetNumber1();
    void SetNumber2(double number);
    double GetNumber2();
    virtual double GetResult() = 0;
};
//加法类
class CAdd : public CAbsOpt{
public:
    double GetResult();
};
//减法类
class CSub : public CAbsOpt{
public:
    double GetResult();
};
//乘法类
class CMul : public CAbsOpt{
public:
    double GetResult();
};
//除法类
class CDiv : public CAbsOpt{
public:
    double GetResult();
};

//简单工厂类
class CSimpleFac{
public:
    static CAbsOpt* Calc(char cOpt);

};


//实现文件

//运算类(其它的加减乘法类从这里继承)
void CAbsOpt::SetNumber1(double number){dNumber1 = number;}
double CAbsOpt::GetNumber1(){return dNumber1;}
void CAbsOpt::SetNumber2(double number){dNumber2 = number;}
double CAbsOpt::GetNumber2(){return dNumber2;}
//加法类
double CAdd::GetResult(){return (dNumber1 + dNumber2);}
//减法类
double CSub::GetResult(){return (dNumber1 - dNumber2);}
//乘法类
double CMul::GetResult(){return (dNumber1 * dNumber2);}
//除法类
double CDiv::GetResult()
{
    const double dZero = 0.000000000000001;
    if((-dZero < dNumber2) && (dNumber2 < dZero))/*除数为0*/    return 0;
    return (dNumber1 / dNumber2);
}

//简单工厂类
CAbsOpt* CSimpleFac::Calc(char cOpt)
{
    CAbsOpt* pOpt = NULL;
    if(cOpt == '+')            pOpt = new CAdd();
    else if(cOpt == '-')        pOpt = new CSub();
    else if(cOpt == '*')        pOpt = new CMul();
    else if(cOpt == '/')        pOpt = new CDiv();
    return pOpt;

}




//测试客户端

void main()
{
    CAbsOpt* pOpt = CSimpleFac::Calc('/');
    pOpt->SetNumber1(12); pOpt->SetNumber2(4);
    cout << pOpt->GetNumber1() << "/" << pOpt->GetNumber2() << " = " << pOpt->GetResult() << endl;
}


阅读更多
版权声明:本文为博主原创文章,允许转载,转载请注明出处。 https://blog.csdn.net/KnightOnHourse/article/details/79959700
上一篇Creational.SingletonPattern单例模式:垃圾回收+线程安全
下一篇简单工厂模式的应用之简单实现ODBC/JDBC驱动管理器的雏形
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭