设计模式-简单工厂模式

适用情景: 根据输入条件的不同,创建不同的类的对象.
缺陷:客户端需要了解基类和工厂类.
这里写图片描述
C++实现:

// coperation.h
#ifndef COPERATION_H
#define COPERATION_H

class COperation
{
public:
    COperation();
public:
    int m_nFirst;
    int m_nSecond;
    virtual double GetResult();
};

#endif // COPERATION_H
// coperation.cpp
#include "coperation.h"

COperation::COperation()
{

}

double COperation::GetResult()
{
    double dResult = 0;
    return dResult;
}
// caddoperation.h
#ifndef CADDOPERATION_H
#define CADDOPERATION_H

#include "coperation.h"

class CAddOperation : public COperation
{
public:
    CAddOperation();
    virtual double GetResult();
};

#endif // CADDOPERATION_H
// caddoperation.cpp
#include "caddoperation.h"

CAddOperation::CAddOperation()
{

}

double CAddOperation::GetResult()
{
    return m_nFirst + m_nSecond;
}

// csuboperation.h
#ifndef CSUBOPERATION_H
#define CSUBOPERATION_H

#include "coperation.h"

class CSubOperation : public COperation
{
public:
    CSubOperation();

    virtual double GetResult();
};

#endif // CSUBOPERATION_H
// csuboperation.cpp
#include "csuboperation.h"

CSubOperation::CSubOperation()
{

}

double CSubOperation::GetResult()
{
    return m_nFirst - m_nSecond;
}

// csimplefactory.h
#ifndef CSIMPLEFACTORY_H
#define CSIMPLEFACTORY_H

#include "coperation.h"

class CSimpleFactory
{
public:
    CSimpleFactory();

public:
    static COperation * Create(char cOperator);
};

#endif // CSIMPLEFACTORY_H
// csimplefactory.cpp
#include "csimplefactory.h"
#include "caddoperation.h"
#include "csuboperation.h"

CSimpleFactory::CSimpleFactory()
{

}

COperation * CSimpleFactory::Create(char cOperator)
{
    COperation * opt;
    switch (cOperator) {
    case '+':
    {
        opt = new CAddOperation();
    }
        break;
    case '-':
    {
        opt = new CSubOperation();
    }
        break;
    default:
        opt = nullptr;
        break;
    }

    return opt;
}

客户端:

// main.cpp
#include <iostream>

#include "coperation.h"
#include "csimplefactory.h"

using namespace std;

int main(int argc, char *argv[])
{
    COperation * opt = CSimpleFactory::Create('+');
    int a, b;
    cin >> a;
    cin >> b;
    opt->m_nFirst = a;
    opt->m_nSecond = b;
    cout << opt->GetResult() << endl;
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值