#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。
參考了《大話設計模式》。