使用pimpl將實現細節移出標頭檔。
將私人成員變數和私人方法移入Impl類,可以實現資料和方法的封裝,以避免在公開標頭檔中聲明私人方法。
不能在實作類別中隱藏虛方法(virtual method),虛方法必須在公開類中出現以便由繼承類重載。
可以在實作類別中加入指向公開類的指標,以便於Impl類調用公開方法。或者也可以將公開類傳給需要它的實作類別方法。
與Bridge Pattern的區別:The Bridge pattern is about object-oriented design, while the PIMPL idiom is about physical design of files.
解釋:
But in its basic and common form, a class using PIMPL points to a single implementation, so there is no abstract class with distinct subclasses — just one class, forward declared, and compiled elsewhere. Changing the implementation class does not require any recompilation of sources that include the main header.
For example, say you have a lot of private member functions, private enums, and private data. And these private "bits" change fairly frequently as the class is developed and maintained. If the #include dependencies are such that touching this header file causes a large number of sources to be recompiled, you have a good candidate for PIMPL.
部署pimpl的方法:Making Pimpl Easy
相關書籍:Large-Scale C++ Software Design
AutoTimer.h
#include <boost/shared_ptr.hpp>class AutoTimer{public:/// Create a new timer object with a human readable name AutoTimer(const std::string &name);/// On destruction, the timer reports how long it was alive~AutoTimer();private:// Make this object be noncopyable because it holds a pointerAutoTimer(const AutoTimer &);const AutoTimer &operator =(const AutoTimer &);class Impl;boost::shared_ptr<Impl> mImpl;};
AutoTimer.cpp
#include "StdAfx.h"#include "AutoTimer.h"#include <iostream>#include <windows.h>#include <string>class AutoTimer::Impl{public:double GetElapsed() const{return (GetTickCount()-mStartTime) / 1e3;}std::string mName;DWORD mStartTime;};AutoTimer::AutoTimer(const std::string &name): mImpl(new AutoTimer::Impl()){mImpl->mName = name;mImpl->mStartTime = GetTickCount();}AutoTimer::~AutoTimer(void){ std::cout<<mImpl->mName<< ": took " << mImpl->GetElapsed() << " secs" << std::endl;}
Main.cpp
#include "stdafx.h"#include "AutoTimer.h"#include <iostream>using namespace std;int _tmain(int argc, _TCHAR* argv[]){AutoTimer timer("MyTimer");for (int i = 0; i < 10000; ++i){cout << ".";}cout << endl;return 0;}