1.桥接模式简介
桥接(Bridge)模式的定义如下:将抽象与实现分离,使它们可以独立变化。它是用组合关系代替继承关系来实现,从而降低了抽象和实现这两个可变维度的耦合度。
2.源码实现
#include <iostream>
#include <string>
using namespace std;
class OS
{
public:
virtual string GetOS() = 0;
};
class IOS : public OS
{
public:
virtual string GetOS()
{
return "IOS Operator System";
}
};
class SaiBian : public OS
{
public:
virtual string GetOS()
{
return "SaiBian Operator System";
}
};
class Phone
{
public:
virtual void SetOS() = 0;
};
class iPhone : public Phone
{
public:
iPhone(OS *os)
{
m_pOS = os;
}
~iPhone(){};
virtual void SetOS()
{
cout << "Set the OS: " << m_pOS->GetOS().c_str() << endl;
}
private:
OS *m_pOS;
};
class Nokia : public Phone
{
public:
Nokia(OS *os)
{
m_pOS = os;
}
~Nokia(){};
virtual void SetOS()
{
cout << "Set the OS: " << m_pOS->GetOS().c_str() << endl;
}
private:
OS *m_pOS;
};
int main(int argc, char **argv)
{
OS *pIOS1 = new IOS();
Phone *iPhone4 = new iPhone(pIOS1);
iPhone4->SetOS();
delete iPhone4;
delete pIOS1;
OS *pSaiBian1 = new SaiBian();
Phone *Nokia1 = new Nokia(pSaiBian1);
Nokia1->SetOS();
delete Nokia1;
delete pSaiBian1;
return 0;
}
3.编译源码
$ g++ -o example example.cpp
4.运行及其结果
$ ./example
Set the OS: IOS Operator System
Set the OS: SaiBian Operator System
网友评论