文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>c++实现简单工厂模式

c++实现简单工厂模式

时间:2011-01-03  来源:ccmfc

#define EPS 0.000000000001

class ArithOpe
{
public:
    virtual double GetArithOpeResult()const
    {
        return 0.0;
    }

    double GetArithOpeNum1()const
    {
        return this->m_num1;
    }
    double GetArithOpeNum2()const
    {
        return this->m_num2;
    }

    void SetArithOpeNum1(const double& num1)
    {
        this->m_num1=num1;
    }
    void SetArithOpeNum2(const double& num2)
    {
        this->m_num2=num2;
    }

private:
    double m_num1;
    double m_num2;
};

class ArithOpeAdd:public ArithOpe
{
    double GetArithOpeResult()const
    {
        return this->GetArithOpeNum1()+this->GetArithOpeNum2();
    }
};

class ArithOpeSub:public ArithOpe
{
    double GetArithOpeResult()const
    {
        return this->GetArithOpeNum1()-this->GetArithOpeNum2();
    }
};

class ArithOpeMul:public ArithOpe
{
    double GetArithOpeResult()const
    {
        return this->GetArithOpeNum1()*this->GetArithOpeNum2();
    }
};

class ArithOpeDiv:public ArithOpe
{
    double GetArithOpeResult()const
    {
        double tmp=this->GetArithOpeNum2()-(int)(this->GetArithOpeNum2());
        if(tmp>=-EPS&&tmp<=EPS)
            return 0.0;
        return this->GetArithOpeNum1()/this->GetArithOpeNum2();
    }
};

class ArithOpeMod:public ArithOpe
{
    double GetArithOpeResult()const
    {
        double tmp=this->GetArithOpeNum2()-(int)(this->GetArithOpeNum2());
        if(tmp>=-EPS&&tmp<=EPS)
            return 0.0;
        return (int)(this->GetArithOpeNum1())%(int)(this->GetArithOpeNum2());
    }
};

#endif // ARITHOPERATOR_H

 

//simply Facotory
#ifndef FACTORY_H
#define FACTORY_H
#include "arithoperator.h"

class ArithOperatorFactory
{
public:
    ArithOpe* CreateArithOperator(const char chsrc)
    {
        ArithOpe* pObject;

        switch(chsrc)
        {
        case '+':
            pObject = new ArithOpeAdd;
            break;
        case '-':
            pObject = new ArithOpeSub;
            break;
        case '*':
            pObject = new ArithOpeMul;
            break;
        case '/':
            pObject = new ArithOpeDiv;
            break;
        case '%':
            pObject = new ArithOpeMod;
            break;

        }

        return pObject;
    }
};

#endif // FACTORY_H

 

 


#include <stdio.h>
#include "factory.h"


int main(int argc, char *argv[])
{
    ArithOperatorFactory Factory;

    ArithOpe *pObj=Factory.CreateArithOperator('/');
    pObj->SetArithOpeNum1(1.1);
    pObj->SetArithOpeNum2(0);

    printf("%0.2f\n", pObj->GetArithOpeResult());
    return 0;
}

相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载