《大话设计模式》- 简单工厂方法 - C++实现

Platform : Linux-Ubuntu 12.04

Tools : VIM + Makefile + (g++)

files:  main.cpp operator.h simple_factory.h


main.cpp

/*************************************************************************
	> File Name: main.cpp
	> Author: banglang
	> Mail: banglang.huang@gmail.com 
	> Created Time: Tue 18 Feb 2014 05:17:11 PM CST
 ************************************************************************/

#include"operator.h"
#include"simple_factory.h"

int main(void)
{
    operation *op = simple_factory::create_operator('+');
    op->setNumberA(1);
    op->setNumberB(7);
    cout<<"result:"<<op->get_result()<<endl;
    return 0;
}


operator.h

#ifndef _OPERATE_H
#define _OPERATE_H

#include<iostream>
using namespace std;

class operation {

    protected:
        double NumberA;
        double NumberB;

    public:
        double getNumberA() {return this->NumberA;}
        double getNumberB() {return this->NumberB;}
        void setNumberA(double v) {this->NumberA = v;}
        void setNumberB(double v) {this->NumberB = v;}
        virtual double get_result()=0;
};

class operationAdd : public operation {

    public:
    double get_result() {
        return (this->NumberA + this->NumberB);
    }
};

#if 0
class minus : public operator {
    public:
    double get_result() {
        return (NumberA - NumberB);
    }
};


class multiple : public operator {
    public:
    double get_result() {
        return (NumberA * NumberB);
    }
};


class divide : public operator {
    public:
    double get_result() {
        if(NumberB == 0)
            throw new Exception("NumberB can not be 0.");
        return (NumberA / NumberB);
    }
};
#endif

#endif /*_OPERATE_H */


simple_factory.h
#ifndef _SIMPLE_FAC_H
#define _SIMPLE_FAC_H

#include "operator.h"

class simple_factory {
    public:
    static operation* create_operator(char c) {
        operation *op = NULL;
        
        switch(c) {
            case '+':
                op = new operationAdd;
                break;
            default:
                cout<<"can not create operatr\n";
                break;
        }

        return op;
    }
};

#endif /* _SIMPLE_FAC_H */



Makefile

all : a

a: main.cpp
	g++ main.cpp -o a


.PHONY : clean
clean:
	rm -rf *.o a *~




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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值