Bridge: Pluggable Implementation
MFC Example of Bridge
In my early days of studying design patterns, I happened to be doing
a fair amount of programming using an early edition of the MFC (Microsoft Foundation Classes).I decided to go looking for patterns in the MFC. Several hours later, I found what I thought was
an example of the Strategy pattern. I later learned from Ralph Johnson that
it was actually an example of a Bridge:
The field,
m_pFile
, plays the role of Implementor:
CArchive::CArchive(CFile* pFile, UINT nMode, int nBufSize, void* lpBuf)
{
// initialize members not dependent on allocated buffer
m_nMode = nMode;
m_pFile = pFile;
…
}
UINT CArchive::Read(void* lpBuf, UINT nMax)
{
…
do
{
nBytes = m_pFile->Read(lpBuf, nLeft);
…
}
while ((nBytes > 0) && (nLeft > 0));
…
}
void CArchive::Write(const void* lpBuf, UINT nMax)
{
…
if (nMax > 0)
{
Flush(); // flush the full buffer // write rest of buffer size chunks
nTemp = nMax - (nMax % m_nBufSize);
m_pFile->Write(lpBuf, nTemp);
lpBuf = (BYTE*)lpBuf + nTemp;
nMax -= nTemp;
…
}
…
}
void CArchive::Flush()
{
…
if (!m_bDirectBuffer)
{
// write out the current buffer to file
m_pFile->Write(m_lpBufStart, m_lpBufCur - m_lpBufStart);
…
}
else
{
// commit current buffer
m_pFile->GetBufferPtr(CFile::bufferCommit, m_lpBufCur - m_lpBufStart);
…
}
…
}
(Reading...)
Formatting Hints:
To format... | use this markup: |
---|---|
source code | {source:lang=java|lineNumbers=false}...{source} (Supported languages: java, cpp, csharp, c, python.) |
bold text | __some text__ |
italicized text | ~~some text~~ |
underlined text | @@some text@@ |
a method or class name | ``myMethod(...)`` |