对于提供给客户使用的类,我们如何把接口与实现分离才能更好的体现软件工程的思想呢。我们一般设计类,把类的定义及接口写到相应的头文件中(*.h这样的文件),而对于类中接口(即方法)的定义则放在*.cpp的源文件中,这样的好处就是类的接口与实现分离,然后对于提供给客户的类,客户还是可以看到类头文件中定义的私有属性。虽然客户不一定会直接修改,但我们还是可以把相应的private属性隐藏,让客户只看到相应类所提供的接口。设计的方法是:设计一个Interface类,在这个类中把private属性定义成一个指向我们要实现隐藏的类指针。相应对要隐藏的类再包装一个类,对于内层要隐藏的类的调用,我们可以通过调用外层接口的方式来完成。
代码如下:
Interface头文件
#ifndef INTERFACE_H
#define INTERFACE_H
class Implementation;//声明一个类类型,无需相应的头文件,此处客户也无法查看相应的Implementation类的信息。
class Interface{
public:
Interface(int);//构造函数
~Interface();//析构函数
int getValue();
void setValue(int);//赋值语句
private:
Implementation *ptr;//指向Implementation类的对象
};
#endif
------------------------------------------------------------------------------------
想要隐藏类的Implementation.h头文件
#ifndef IMPLEMENTATION_H
#define IMPLEMENTATION_H
class Implementation{
public:
Implementation(int);//默认构造函数
int getValue();//获得value
void setValue(int);//设置相应的value
private:
int value;
};
#endif
--------------------------------------------------------------------------------------
Implementation.cpp源文件的实现
#include <iostream>
#include "Implementation.h"
using namespace std;
Implementation::Implementation( int i)//构造函数
:value(i)
{
//empty
}
int Implementation::getValue()
{
return value;
}
void Implementation::setValue( int i)
{
value = i;//设置相应的函数
}
-----------------------------------------------------------------------------------
Interface.cpp源文件的实现
#include <iostream>
#include "Implementation.h" //有人可能会说,从Interface.cpp还是可以看到相应的Implementation类的定义的
#include "Interface.h" //其实这个地方的Interface.cpp最后是以目标代码的方式提供调用的,不会直接提供源代码的
using namespace std; //所有这个很安全
Interface::Interface( int i)
:ptr(new Implementation(i))//默认构造函数,调用初始化列表器
{
//empty
}
Interface::~Interface()
{
delete ptr;//释放相应内存
}
int Interface::getValue()
{
return ptr->getValue();//返回相应的value值
}
void Interface::setValue(int i)
{
ptr->setValue(i);
}
---------------------------------------------------------------------
main.cpp源文件的实现
#include <iostream>
#include "Interface.h"//这时,客户代码只能看到Interface.h这个头文件,后面的真正的Implementation类被隐藏
using namespace std;
int main(){
Interface a1(123);
cout<<"a1 have value :"<<a1.getValue()<<endl;//a1取值真正来自Implementation
}
main.cpp源文件的实现完全隐藏了Implementation类的存在