工厂模式

参考《大话设计模式》
工厂模式常用来实例化对象,但与此同时,程序在可扩展性和修改量上会有更大的提升。下面是大话设计模式里的例子,我自己实现了一遍,作为参考:

#include <iostream>
using namespace std;
//运算基类
class operation
{
public:
    double numa;
    double numb;
    virtual double getResults(){return 0;};
};

//运算类,单独写的目的是将来如果需要添加新的运算符的话,那么就只需要直接添加一个运算类继operation就行了
//加法类
class operationAdd:public operation
{
public:
    double getResults()
    {
        return numa+numb;
    }
};
//减法类
class operationMin:public operation
{
public:
    double getResults()
    {
        return numa-numb;
    }
};
//乘法类
class operationMul:public operation
{
public:
    double getResults()
    {
        return numa*numb;
    }
};
//除法类
class operationDiv:public operation
{
public:
    double getResults()
    {
        if(0 == numb)
            return 0;
        return numa/numb;
    }
};
//幂次方类
class operationSquare:public operation
{
    double getResults()
    {
        double sum = 1;
        for(int i=0; i<numb; i++)
          sum = sum * numa;
        return sum;
    }
};

//类工厂,为了返回需要的运算类
class operationFactory
{
public:
    operation *createOperation(char operate)
    {
        operation *oper;
        switch(operate)
        {
        case 43:
            oper = new operationAdd();
            break;
        case 45:
            oper = new operationMin();
            break;
        case 42:
            oper = new operationMul();
            break;
        case 47:
            oper = new operationDiv();
            break;
        case 94:
            oper = new operationSquare();
            break;
        default:
            oper = NULL;
            cout << "please input the right operation"<< endl;
            break;
        }
        return oper;
    }
};

int main()
{
    operation *op;
    operationFactory *of = new operationFactory();
    op = of->createOperation('^');
    op->numa = 2;
    op->numb = 3;
    cout << op->getResults() << endl;
}

程序首先声明一个运算基类,包含操作数和结果。不同的运算类继承运算基类,但是每个运算类的getResults()写不同的代码达到不同的运算。这样的设计还没有什么优势,比如我还是需要根据不同的操作符生成不同的对象,在主程序中我可能会写出这样的代码:

switch(oper)
{
case 43:
    //声明一个加法对象
    break;
...
}

这样做的坏处是出程序里会显的很冗余,而且如果添加了新的运算的花,还需要在主程序里改动。我们需要的是一种机制,可以通过不同的运算符返回不同的对象。所以我们再写一个类(工厂类),用来生成各种各样的对象。
现在程序的结构就非常清晰了,扩展性也相当的好。如果我现在需要添加新的运算符的话,比如开方,那么我只需要在相应的位置增加下列代码:

class operationKaifang:public operation
{
    double getResults()
    {
        //逻辑代码
    }
}
//在工厂类里的swtich里添加:
case 83:    //假设用s作为开方符号,s对应的ascii为83
    oper = new operationKiafang();
    break;

定义这些之后,主程序传入’s’就可以得到结果了。这样就真正的分离了用户输入和运算,程序扩展性大大提高。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值