//
// main.cpp
// test
//
// Created by sun on 15/11/14.
// Copyright (c) 2015年 sun. All rights reserved.
//
#include <iostream>
using namespace std;
int main(int argc, const char * argv[])
{
int a;
printf("请输入数字a:
");
scanf("%d",&a);
int symbol;
printf("请输入运算符(+-*/):
");
scanf("%d",&symbol);
printf("请输入数字b:
");
int b;
scanf("%d",&b);
cout<<"result:";
switch (symbol) {
case 1:
cout<<a+b<<endl;
break;
case 2:
cout<<a-b<<endl;
break;
case 3:
cout<<a*b<<endl;
break;
case 4:
cout<<a/b<<endl;
break;
default:
break;
}
return 0;
}
工厂模式
//
// main.cpp
// test
//
// Created by sun on 15/11/14.
// Copyright (c) 2015年 sun. All rights reserved.
//
#include <iostream>
using namespace std;
class Operation
{
public:
double _a;
double _b;
Operation()
{
}
virtual double GetResult()
{
double result=0;
return result;
}
};
class OperationAdd:public Operation
{
public:
OperationAdd()
{
Operation();
}
double GetResult ()
{
return _a+_b;
}
};
class OperationSub:public Operation
{
public:
OperationSub()
{
Operation();
}
double GetResult ()
{
return _a-_b;
}
};
class OperationFactory
{
public:
static Operation* create(int operate)
{
Operation* oper;
switch (operate) {
case 1:
oper=new OperationAdd();
break;
case 2:
oper=new OperationSub();
break;
default:
break;
}
return oper;
}
};
int main(int argc, const char * argv[])
{
Operation* oper;
oper=OperationFactory::create(2);
oper->_a=1;
oper->_b=3;
cout<<oper->GetResult()<<endl;
return 0;
}