设计模式--简单工厂模式

通过对计算器的算法实现抽象,封装,继承,但通过调用积累获取结果时不知道去实例化哪个算法,这里引入了简单的工厂模式,通过运算符的不同去实例化不同算法类,然后去设置值进行运算,代码如下:

// SimpleFactory.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <Windows.h>
class IAlgorithm
{
public:
    IAlgorithm():m_a(0),m_b(0){};
    virtual double GetResutl() = 0;
    void setA(double a){m_a = a;};
    void setB(double b){m_b = b;};
    double getA(){return m_a;};
    double getB(){return m_b;};
private:
    double m_a;
    double m_b;
};
class CAddition : public IAlgorithm
{
public:
    virtual double GetResutl()
    {
        return getA() + getB();
    };
};

class CSubtraction :public IAlgorithm
{
public:
    virtual double GetResutl()
    {
        return getA() - getB();
    };
};

class CMultiplication : public IAlgorithm
{
public:
    virtual double GetResutl()
    {
        return getA() * getB();
    };
};

class CDivision : public IAlgorithm
{
public:
    virtual double GetResutl()
    {
        return getA() / getB();
    };
};

class CSimpleFactory
{
public:
    static IAlgorithm *createOperate(char ch)
    {
        IAlgorithm *pAlgo;
        switch (ch)
        {
        case '+':
            pAlgo = new CAddition();
            break;
        case '-':
            pAlgo = new CSubtraction();
            break;
        case '*':
            pAlgo = new CMultiplication();
            break;
        case '/':
            pAlgo = new CAddition();
            break;
        }
        return pAlgo;
    }

};

int _tmain(int argc, _TCHAR* argv[])
{
    IAlgorithm *pAlgorithm = CSimpleFactory::createOperate('+');
    pAlgorithm->setA(10);
    pAlgorithm->setB(20);

    double val = pAlgorithm->GetResutl();

    getchar();
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值