桥接模式使基于类的最小设计原则,通过封装、聚合以及继承等行为来让不同的类承担不同的责任。它的主要特点是把抽象和行为的具体实现分割开来,从而保证各部分的独立性以应对他们的功能扩展。即这种模式涉及到一个作为桥接的接口,使得实体类的功能独立于接口实现类。也就是说将他们之间的强关联变成弱关联,即在一个软件系统内的抽象化和实现化之间使用组合聚合关系,而不是继承。从而使得这两种类型的类可被结构化改变而互不影响。

优点: 1、抽象和实现的分离。 2、优秀的扩展能力。 3、实现细节对客户透明。

缺点:桥接模式的引入会增加系统的理解与设计难度,由于聚合关联关系建立在抽象层,要求开发者针对抽象进行设计与编程。

类图如下:

示例代码如下:

#include <iostream>
#include <string>

using namespace std;


class Software
{
public:
	virtual void run() = 0;
};

class SoftwareGame : public Software
{
public:
	void run()
	{
		std::cout << "游戏软件" << std::endl;
	}
};

class SoftwareNote : public Software
{
public:
	void run()
	{
		std::cout << "记事本软件" << std::endl;
	}
};
//
class Computer
{
protected:
	Software * m_software;
public:
	Computer() : m_software(NULL){}
	virtual ~Computer()
	{
		if (NULL != m_software)
		{
			delete m_software;
		}
	}
	virtual void run() = 0;
	void setSoftware(Software *p)
	{
		m_software = p;
	}
};

class ComputerLenovo : public Computer
{
public:
	void run()
	{
		std::cout << "联想的电脑运行";
		m_software->run();
	}
};

class ComputerMirco : public Computer
{
public:
	void run()
	{
		std::cout << "微软的电脑运行";
		m_software->run();
	}
};


int main()
{
	using namespace std;
	// 桥接模式
	Computer *p = new ComputerLenovo();
	p->setSoftware(new SoftwareGame());
	p->run();
	delete p;

	p = new ComputerMirco();
	p->setSoftware(new SoftwareNote());
	p->run();
	delete p;

	system("pause");
	return 0;
}

运行结果如下: