文章目录
一、多态实现一个计算器
- 多态的优点:
组织结构清晰
,可读性好
,方便扩展和维护
分别使用,普通和多态实现一个计算器,体会一下多态带来的好处
1.1 普通实现
//多态的优点:组织结构清晰,可读性好,方便扩展和维护
//分别使用,普通和多态实现一个计算器,体会一下多态带来的好处
//普通实现
#include <iostream>
using namespace std;
#include <string>
class Calculator
{
public:
int num1;
int num2;
//只有加减乘运算,如果后续需要增加减法,需要修改compute函数代码,不易扩展和维护
int compute(string operation)
{
if (operation == "+")
return num1 + num2;
else if (operation == "-")
return num1 - num2;
else if (operation == "*")
return num1 * num2;
else
{
cout << "NO this Operation,Error
";
exit;
}
}
};
void test()
{
Calculator c;
c.num1 = 100;
c.num2 = 200;
cout << c.compute("+") << endl << c.compute("-") << endl << c.compute("*") << endl;
}
int main()
{
test();
return 0;
}
1.2 多态实现
#include <iostream>
using namespace std;
//多态来实现计算器
class AbstractCalculator
{
public:
int num1;
int num2;
//虚函数,用户实现多态
virtual int compute()
{
return 0;
}
};
class AddCalculator : public AbstractCalculator
{
public:
virtual int compute()
{
return num1 + num2;
}
};
class DelCalculator : public AbstractCalculator
{
public:
virtual int compute()
{
return num1 - num2;
}
};
class MulCalculator : public AbstractCalculator
{
public:
int compute()
{
return num1 * num2;
}
};
//这里可以很方便的来扩展除法,而不需要修改上面的代码。如果哪个出现问题可以快速定位
class DivCalculator : public AbstractCalculator
{
public:
int compute()
{
return num1 / num2;
}
};
void test2()
{
AbstractCalculator* abc = new AddCalculator;
abc->num1 = 200;
abc->num2 = 100;
cout << abc->compute() << endl;
delete abc;
abc = new DelCalculator;
abc->num1 = 200;
abc->num2 = 100;
cout << abc->compute() << endl;
delete abc;
abc = new MulCalculator;
abc->num1 = 200;
abc->num2 = 100;
cout << abc->compute() << endl;
delete abc;
abc = new DivCalculator;
abc->num1 = 200;
abc->num2 = 100;
cout << abc->compute() << endl;
delete abc;
}
int main()
{
test2();
return 0;
}