// TestInterface.h
//-------------------------------------------------------------------
class TestImpl;
class TestInterface
{
public:
explicit TestInterface( int index );
~TestInterface();
int GetIndex();
private:
TestImpl *impl_;
};
//-------------------------------------------------------------------
这个例子包括一个接口类TestInterface,一个实现类TestImpl,每个类有一个头文件及一个实现文件,外加一个main.cpp
接口部分:
// TestInterface.cpp
//-------------------------------------------------------------------
#include "TestInterface.h "
#include "TestImpl.h "
TestInterface::TestInterface( int index ) : impl_( new TestImpl( index ) ) //匆忙写的,new就没做异常处理了
{
}
TestInterface::~TestInterface()
{
delete impl_;
}
int TestInterface::GetIndex()
{
return impl_-> GetIndex();
}
//-------------------------------------------------------------------
实现部分:
// TestImpl.h
//-------------------------------------------------------------------
class TestImpl
{
public:
explicit TestImpl( int index );
int GetIndex();
private:
int index_;
};
//-------------------------------------------------------------------
// TestImpl.cpp
//-------------------------------------------------------------------
#include "TestImpl.h "
TestImpl::TestImpl( int index ) : index_( index )
{
}
int TestImpl::GetIndex()
{
return index_;
}
//-------------------------------------------------------------------
这样,接口与实现就实现了分离,使用者不需要知道TestImpl到底是按照什么算法给出index的,它只需要调用TestInterface的GetIndex函数即可,如下:
// main.cpp
//-------------------------------------------------------------------
#include <iostream>
#include "TestInterface.h "
int main()
{
TestInterface indexTest( 123 );
std::cout < < indexTest.GetIndex() < < std::endl;
return 0;
}
//-------------------------------------------------------------------
这样,即使实现类TestImpl决定增加一个增量indexIncrement_,每次返回的index都必须和这个增加相加,如下:
// TestImpl.h
//-------------------------------------------------------------------
class TestImpl
{
public:
explicit TestImpl( int index );
int GetIndex();
private:
int index_;
int indexIncrement_;
};
//-------------------------------------------------------------------
// TestImpl.cpp
//-------------------------------------------------------------------
#include "TestImpl.h "
TestImpl::TestImpl( int index ) : index_( index ), indexIncrement_( 2 )
{
}
int TestImpl::GetIndex()
{
return index_ + indexIncrement_;
}
//-------------------------------------------------------------------
那么main.cpp也同样不需要重新编译,需要重新编译的,只有TestImpl本身(这个必然),以及TestInterface.cpp,而所有include了TestInterface.h的文件,比如main.cpp,完全不需要重新编译。
这是一个小程序,所以这么写可能未必能让人觉得有多好,但是如果是大项目,很多地方相互依赖的话,从设计上来说,可维护性就不强,而且编译依赖严重的话,修改一个地方导致半个小时的重新编译,这个是不可忍受的。
这里只有一个main.cpp用到了TestInterface这个接口,但是如果有1000个文件用到了,那样会是什么情况?呵呵