设计模式之桥接模式

桥接模式是将抽象部分与它的实现部分分离,使它们都可以独立地变化。

例如现在的手机硬件与软件,电脑硬件和软件,都是通过不同的厂商来开发的。它们之间都不是谁依赖谁的关系,都是往中间抽象层依靠。

手机与软件实现:

//合成/聚合复用原则:尽量使用合成/聚合,尽量不要使用类继承
#include <iostream>

using namespace std;

class HandsetSoft
{
public:
		virtual void Run() = 0;
};

//手机游戏
class HandsetGame : public HandsetSoft
{
public:
	void Run()
	{
		cout << "运行手机游戏" << endl;
	}
};

//手机通讯录
class HandsetAddressList : public HandsetSoft
{
public:
	void Run()
	{
		cout << "运行手机通讯录" << endl;
	}
};

//手机品牌
class HandsetBrand
{
public:
		void SetHandsetSoft(HandsetSoft* soft)
		{
			this->soft = soft;			
		}
		virtual void Run()= 0;
protected:
	HandsetSoft* soft;
};


class HandsetBrandN : public HandsetBrand
{
public:
	void Run()
	{
		soft->Run();
	}
};


class HandsetBrandM : public HandsetBrand
{
public:
	void Run()
	{
		soft->Run();
	}
};


int main()
{
	HandsetBrand* ab = new HandsetBrandN();
	
	ab->SetHandsetSoft(new HandsetGame());
	ab->Run();
	
	ab->SetHandsetSoft(new HandsetAddressList());
	ab->Run();
	
	ab = new HandsetBrandM();
	
	ab->SetHandsetSoft(new HandsetGame());
	ab->Run();
	
	ab->SetHandsetSoft(new HandsetAddressList());
	ab->Run();
	
}

电脑与系统的实现:

//操作系统--电脑

#include <iostream>

using namespace std;

class OS
{
	public:
		virtual void OS_operation() = 0;
};

class Windows : public OS
{
	void OS_operation()
	{
		cout << "Windows" << endl;
	}
};

class Linux : public OS
{
	void OS_operation()
	{
		cout << "Linux" << endl;
	}
};

class Unix : public OS
{
	void OS_operation()
	{
		cout << "Unix" << endl;
	}
};

class Computer
{
	public:
		virtual void InstallOS(OS* os) = 0;
};

class HuaweiComputer : public Computer
{
	void InstallOS(OS* os)
	{
		os->OS_operation();
	}
};

class AppleComputer : public Computer
{
	void InstallOS(OS* os)
	{
		os->OS_operation();
	}
};

class QilinComputer : public Computer
{
	void InstallOS(OS* os)
	{
		os->OS_operation();
	}
};

int main()
{
	OS* os1 = new Windows();
	OS* os2 = new Linux();
	OS* os3 = new Unix();
	Computer* computer1 = new HuaweiComputer();
	Computer* computer2 = new AppleComputer();
	Computer* computer3 = new QilinComputer();
	
	computer1->InstallOS(os1);
	computer2->InstallOS(os3);
	computer3->InstallOS(os2);
	
	
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值