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 */
#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 *~