PIMPL模式

今天在复习资料的时候接触到了PIMPL模式,觉得有点陌生,遂对其进行了一点点研究。以下是个人的理解,可能会有比较片面的地方。

PIMPL(Private Implementation),是由Herb Sutter介绍的一种C++编程惯用法,这种方法通过一个私有的成员pimpl指针,将指针所指向的类的内部实现数据进行隐藏。这样做的意义在于:

  1.降低了不同类之间的耦合,因为隐藏了类的实现,被隐藏的类就相对于原类不可见,所以隐藏类进行修改,不需要重新编译原类。

  2.由于减少了编译的代码量,只进行部分编译,直接导致了编译速度的提高。

  3.不可见的类的内部实现,通过指针封装,使接口的稳定性得到保证。(因为不能修改内部的实现了嘛,这是显而易见的)

以下是代码示例:

foo.h
 1 //here just declare the class PIMPL to compile. 
 2 //As I use this class with a pointer, I can use this declaration 
 3 class CFoo_pimpl; 
 4  
 5 class CFoo
 6 {
 7 public:
 8     CFoo();
 9     ~CFoo();
10     bool ProcessFile(const CString & csFile);
11 private:
12     std::auto_ptr<CFoo_pimpl>    m_pImpl;
13 }

foo.h中使用了一个交叉类,因为头文件中申明了CFoo_pimpl类型的指针

foo.cpp
 1 #include "FooInternalData.h"
 2 #include "Header.h"
 3 #include "foo.h"
 4 
 5 //here defines PIMPl class, because it is use only in this file
 6 class CFoo_pimpl()
 7 {
 8 public:
 9     CFoo_pimpl()
10     {
11     }
12  
13     ~CFoo_pimpl()
14     {
15     }  
16     bool ProcessFile(const CString & csFile)
17     {
18         //do something
19         return true;
20     }
21 };
22  
23 CFoo::CFoo()
24 :m_pImpl(new CFoo_pimpl())
25 {
26 }
27  
28 CFoo::~CFoo()
29 {
30     //do not have to delete, std::auto_ptr is very nice 
31 }
32  
33 bool CFoo::ProcessFile(const CString & csFile)
34 {
35     //just call your PIMPL function ;-)
36     return m_pImpl->ProcessFile(csFile);
37 }

foo.cpp中CFoo_pimpl类的方法ProcessFile(const CString & csFile)被封装在CFoo::ProcessFile(const CString & csFile)中,使得CFoo::ProcessFile(const CString & csFile)的内部实现被隐藏

这样在main方法中就可以按照以下进行调用:

main.cpp
1 #include "foo.h"
2  
3 int main() 
4 {
5     CFoo foo;
6     foo.ProcessFile("c:\\data.bin");
7     return 0; 
8 } 

在main方法中,虽然调用的是CFoo类的对象的方法ProcessFile(const CString & csFile),可是实际的内部实现是CFoo_pimpl类的方法ProcessFile(const CString & csFile),但对于CFoo类来说,这个实现是不可见的。

假设CFoo_pimpl类的方法ProcessFile(const CString & csFile)的实现因为需求变更发生了改变,则这样的情况下,CFoo类的私有成员指针m_pImpl并没有改变(指针一般依据平台)。所以客户的CFoo.cpp文件并不需要重新编译。这在实际开发中是非常有意义的。这种模式的实例在BOOST中非常常见。

 

 

 

 

 

posted on 2012-08-30 23:47  二白  阅读(292)  评论(0编辑  收藏  举报