前言
在一些大型C++项目中,学习C++的设计模式对于提高代码能力而言十分重要,这个专栏主要用于讲解C++语言常用的设计模式,对于优化代码结构,理解C++语言的逻辑结构而言十分重要。
开闭原则
开闭原则主要概括为:对扩展开放,对修改关闭。
增加功能是通过增加代码实现的,而不是修改源代码。
修改源代码及其容易犯错,若项目文件过大时,类与类的关联性强,改的地方就会特别多。一个类最好只做一件事情。
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
//相机类
class Camera
{
private:
int m_gainValue;
int m_exposureValue;
string m_operator;
public:
int getResult()
{
if (m_operator.compare("+")==0)
{
return m_exposureValue + m_gainValue;
}
if (m_operator.compare("-") == 0)
{
return m_exposureValue - m_gainValue;
}
if (m_operator.compare("*") == 0)
{
return m_exposureValue * m_gainValue;
}
if (m_operator.compare("/") == 0)
{
return m_exposureValue / m_gainValue;
}
}
Camera(int gainValue, int exposureValue, string strOperator)
{
this->m_exposureValue = exposureValue;
this->m_gainValue = gainValue;
this->m_operator = strOperator;
}
};
//测试相机类的函数
void test01()
{
Camera *pCamera = new Camera(10, 20, "+");
cout << pCamera->getResult() << endl;
delete pCamera;
}
int _tmain(int argc, _TCHAR* argv[])
{
test01();
system("pause");
return 0;
}
以上代码如果要更改对相机类参数的操作,比如更改曝光值等,需要找到getResult函数并且更改源代码,这样就会有增加出错的可能性。在增加新功能的需求时,最好是另外再写一个类增加功能,不改变现有的类,这样的原则便是开闭原则。即对修改关闭,对扩展开放。
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
//增加新功能,添加相机类曝光参数公式的修改;
//第一步,写一个抽象相机类
class BaseCamera
{
public:
virtual int getResult()=0;
virtual void setCameraValue(int gainValue, int exposureValue) = 0;
};
//修改相机类,增加新功能---参数相加
class AddCamera :public BaseCamera
{
public:
int m_gainValue;
int m_exposureValue;
void setCameraValue(int gainValue,int exposureValue)
{
m_exposureValue = exposureValue;
m_gainValue = gainValue;
}
virtual int getResult()
{
return m_exposureValue + m_gainValue;
}
};
//修改相机类,增加新功能----参数相减
class SubCamera :public BaseCamera
{
public:
int m_gainValue;
int m_exposureValue;
void setCameraValue(int gainValue, int exposureValue)
{
m_exposureValue = exposureValue;
m_gainValue = gainValue;
}
virtual int getResult()
{
return m_exposureValue - m_gainValue;
}
};
//以上是根据抽象基类,增加了新功能,增加两个新的类,每个类有专门的作用
//虽然有点简单问题复杂化,但是没有修改基类。
//同时使用virtual实现了多态。
//测试相机类的函数
void test02()
{
//使用抽象基类,抽象类不能实例化对象
BaseCamera *pBaseCamera = new AddCamera();
pBaseCamera->setCameraValue(10, 20);
cout << pBaseCamera->getResult() << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
test02();
system("pause");
return 0;
}
根据以上的代码可以看出,若增加相机类的接口函数功能,只需要增加一个相机类,重写纯虚函数,并不需要更改源代码,更方便代码的维护。