桥接模式的意图是将抽象部分与实现部分分离,使它们都可以独立的变化。
先附上其结构图:
以一个日志记录工具这个例子来说明Bridge模式,现在我们要开发一个通用的日志记录工具,它支持数据库记录DatabaseLog和文本文件记录FileLog两种方式,同时它既可以运行在.NET平台,也可以运行在Java平台上。
我们把日志记录方式和不同平台上的实现分别当作两个独立的部分来对待,Log及ImpLog,Log是日志记录方式,ImpLog是日志记录在不同平台的实现的基类,结构图如下:
实现代码:
//ImpLog.h
class ImpLog
{
public:
virtual ~ImpLog();
virtual void WriteLog() = 0;
protected:
ImpLog();
};
//ImpLog.cpp
#include "stdafx.h"
#include "ImpLog.h"
ImpLog::ImpLog()
{
}
ImpLog::~ImpLog()
{
}
//NImpLog.h
#include "ImpLog.h"
class NImpLog : public ImpLog
{
public:
NImpLog();
virtual ~NImpLog();
void WriteLog();
};
//NImpLog.cpp
#include "stdafx.h"
#include "NImpLog.h"
#include <iostream>
using namespace std;
NImpLog::NImpLog()
{
}
NImpLog::~NImpLog()
{
}
void NImpLog::WriteLog()
{
cout << "在.NET下写日志" << endl;
}
//JImpLog.h
#include "ImpLog.h"
class JImpLog : public ImpLog
{
public:
JImpLog();
virtual ~JImpLog();
void WriteLog();
};
//JImpLog.cpp
#include "stdafx.h"
#include "JImpLog.h"
#include <iostream>
using namespace std;
JImpLog::JImpLog()
{
}
JImpLog::~JImpLog()
{
}
void JImpLog::WriteLog()
{
cout << "在Java下写日志" << endl;
}
//Log.h
class ImpLog;
class Log
{
public:
virtual ~Log();
virtual void Write() = 0;
protected:
Log();
};
//Log.cpp
#include "stdafx.h"
#include "Log.h"
Log::Log()
{
}
Log::~Log()
{
}
//DBLog.h
#include "Log.h"
class DBLog : public Log
{
public:
DBLog();
DBLog(ImpLog*);
virtual ~DBLog();
void Write();
private:
ImpLog* m_pImpLog;
};
//DBLog.cpp
#include "stdafx.h"
#include "DBLog.h"
#include "ImpLog.h"
#include <iostream>
using namespace std;
DBLog::DBLog()
{
}
DBLog::DBLog(ImpLog* pImpLog) : m_pImpLog(pImpLog)
{
}
DBLog::~DBLog()
{
if(m_pImpLog != NULL)
{
delete m_pImpLog;
m_pImpLog = NULL;
}
}
void DBLog::Write()
{
cout << "数据库日志:";
m_pImpLog->WriteLog();
}
//TxtLog.h
#include "Log.h"
class TxtLog : public Log
{
public:
TxtLog();
TxtLog(ImpLog*);
virtual ~TxtLog();
void Write();
private:
ImpLog* m_pImpLog;
};
//TxtLog.cpp
#include "stdafx.h"
#include "TxtLog.h"
#include "ImpLog.h"
#include <iostream>
using namespace std;
TxtLog::TxtLog()
{
}
TxtLog::TxtLog(ImpLog* pImpLog) : m_pImpLog(pImpLog)
{
}
TxtLog::~TxtLog()
{
if(m_pImpLog != NULL)
{
delete m_pImpLog;
m_pImpLog = NULL;
}
}
void TxtLog::Write()
{
cout << "文本日志:";
m_pImpLog->WriteLog();
}
//main.cpp
#include "stdafx.h"
#include "Log.h"
#include "DBLog.h"
#include "TxtLog.h"
#include "ImpLog.h"
#include "NImpLog.h"
#include "JImpLog.h"
int main(int argc, char* argv[])
{
ImpLog* pImp = new NImpLog;
Log* pLog = new DBLog(pImp);
pLog->Write();
pLog = new TxtLog(pImp);
pLog->Write();
pImp = new JImpLog;
pLog = new DBLog(pImp);
pLog->Write();
pLog = new TxtLog(pImp);
pLog->Write();
return 0;
}
最后输出为:
数据库日志:在.NET下写日志
文本日志:在.NET下写日志
数据库日志:在Java下写日志
文本日志:在Java下写日志
更详细信息请参考:
http://terrylee.cnblogs.com/archive/2006/02/24/336652.html