//开闭原则 对扩展放,对修改关闭,增加功能是通过增加代码来实现的,而不是去修改源代码
//简单的问题复杂化,但是好维护和增加功能
# include <iostream>
using namespace std;
//写一个抽象类
class AbstractCaculator
{
public:
virtual int getResult() = 0;
virtual void setOperatorNumber(int a, int b) = 0;
};
//加法计算器类
class PlusCaculatir: public AbstractCaculator
{
public:
virtual void setOperatorNumber(int a, int b)
{
this->mA = a;
this->mB = b;
}
virtual int getResult()
{
return mA + mB;
}
private:
int mA;
int mB;
};
//减法计算器类
class MinuteCaculatir: public AbstractCaculator
{
public:
virtual void setOperatorNumber(int a, int b)
{
this->mA = a;
this->mB = b;
}
virtual int getResult()
{
return mA - mB;
}
private:
int mA;
int mB;
};
//乘法计算器类
class MultiplyMinuteCaculatir: public AbstractCaculator
{
public:
virtual void setOperatorNumber(int a, int b)
{
this->mA = a;
this->mB = b;
}
virtual int getResult()
{
return mA * mB;
}
private:
int mA;
int mB;
};
//取模计算器类 通过增加代码来实现
class QumoCaculatir: public AbstractCaculator
{
public:
virtual void setOperatorNumber(int a, int b)
{
this->mA = a;
this->mB = b;
}
virtual int getResult()
{
return mA % mB;
}
private:
int mA;
int mB;
};
void test01()
{
AbstractCaculator *caculator = new PlusCaculatir;
caculator->setOperatorNumber(10, 20);
cout << caculator->getResult() << endl;
delete caculator;
caculator = new MinuteCaculatir;
caculator->setOperatorNumber(10, 20);
cout << caculator->getResult() << endl;
}
int main(int argc, char *argv[])
{
test01();
return 0;
}
//简单的问题复杂化,但是好维护和增加功能
# include <iostream>
using namespace std;
//写一个抽象类
class AbstractCaculator
{
public:
virtual int getResult() = 0;
virtual void setOperatorNumber(int a, int b) = 0;
};
//加法计算器类
class PlusCaculatir: public AbstractCaculator
{
public:
virtual void setOperatorNumber(int a, int b)
{
this->mA = a;
this->mB = b;
}
virtual int getResult()
{
return mA + mB;
}
private:
int mA;
int mB;
};
//减法计算器类
class MinuteCaculatir: public AbstractCaculator
{
public:
virtual void setOperatorNumber(int a, int b)
{
this->mA = a;
this->mB = b;
}
virtual int getResult()
{
return mA - mB;
}
private:
int mA;
int mB;
};
//乘法计算器类
class MultiplyMinuteCaculatir: public AbstractCaculator
{
public:
virtual void setOperatorNumber(int a, int b)
{
this->mA = a;
this->mB = b;
}
virtual int getResult()
{
return mA * mB;
}
private:
int mA;
int mB;
};
//取模计算器类 通过增加代码来实现
class QumoCaculatir: public AbstractCaculator
{
public:
virtual void setOperatorNumber(int a, int b)
{
this->mA = a;
this->mB = b;
}
virtual int getResult()
{
return mA % mB;
}
private:
int mA;
int mB;
};
void test01()
{
AbstractCaculator *caculator = new PlusCaculatir;
caculator->setOperatorNumber(10, 20);
cout << caculator->getResult() << endl;
delete caculator;
caculator = new MinuteCaculatir;
caculator->setOperatorNumber(10, 20);
cout << caculator->getResult() << endl;
}
int main(int argc, char *argv[])
{
test01();
return 0;
}