#include<iostream>
#include<string>
#include<cstdlib>
using namespace std;
/*
简单工厂模式实现简单计算器程序
*/
class super_compute //抽象产品角色
{
private:
int a;
int b;
public:
void set_a(int value)
{a = value;}
void set_b(int value)
{b = value;}
int get_a()
{
return a;
}
int get_b()
{
return b;
}
virtual int get_result() //动态绑定条件1
{
double result = 0;
return result;
}
super_compute& operator= (const super_compute& rhs)
{
a = rhs.a;
b = rhs.b;
return *this;
}
};
/* 具体产品角色*/
class add_operator: public super_compute
{
public:
add_operator(int a, int b)
{
set_a(b);
set_b(b);
}
int get_result()
{
return get_a() + get_b();
}
};
class sub_operator: public super_compute
{ public:
sub_operator(int a, int b)
{
set_a(b);
set_b(b);
}
int get_result()
{
return get_a() - get_b();
}
};
class muti_operator: public super_compute
{ public:
muti_operator(int a, int b)
{
set_a(b);
set_b(b);
}
int get_result()
{
return get_a()*get_b();
}
};
class div_operator: public super_compute
{ public:
div_operator(int a, int b)
{
set_a(b);
set_b(b);
}
int get_result()
{
return get_a()/get_b();
}
};
/*生产者角色*/
class factory
{ public:
void creat_operator(int a, int b, char op)
{
super_compute *ob; //动态绑定
switch(op)
{
case '+':
ob = new add_operator(a,b);
break;
case '-':
ob = new sub_operator(a,b);
break;
case '*':
ob = new muti_operator(a,b);
break;
case '/':
ob = new div_operator(a,b);
break;
default:
cout << "operator erro , please check."<< endl;
}
cout << "The result is "<<ob->get_result()<< endl; //动态绑定条件2
}
};
int main()
{
long int a,b,result;
char op;
cout << " Input the first number :"<< endl;
cin >> a;
cout << "Input the operator:"<< endl;
cin >> op;
cout << "Input the second number :" << endl;
cin >> b;
factory fac;
fac.creat_operator(a,b,op);
system("pause");
return 0;
}
总结:oo的精髓是可复用、易维护和可扩展。知道了OCP原则。
C++ 动态绑定的条件 1、只有指定为虚函数的成员函数才能进行动态绑定 2、必须通过基类类型的引用或指针才能进行函数调用。详解见《C++primer》中文版 P479。