设计模式读书笔记:Bridge(桥接)

意图:

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

结构图:来自 《23种设计模式 - 郗晓勇》


实现:https://github.com/panshiqu/patterns/tree/master/Bridge

Implementor

namespace NS_BRIDGE {

class Implementor {
public:
	Implementor() {}
	virtual ~Implementor() {}
	virtual void operationImp(void) = 0;
};

} /* namespace NS_BRIDGE */
ConcreteImplementorA

#include "Implementor.h"
#include <iostream>

namespace NS_BRIDGE {

class ConcreteImplementorA : public Implementor
{
public:
	ConcreteImplementorA() {}
	virtual ~ConcreteImplementorA() {}
	virtual void operationImp(void)
	{
		std::cout << "ConcreteImplementorA" << std::endl;
	}
};

} /* namespace NS_BRIDGE */
ConcreteImplementorB

#include "Implementor.h"
#include <iostream>

namespace NS_BRIDGE {

class ConcreteImplementorB : public Implementor
{
public:
	ConcreteImplementorB() {}
	virtual ~ConcreteImplementorB() {}
	virtual void operationImp(void)
	{
		std::cout << "ConcreteImplementorB" << std::endl;
	}
};

} /* namespace NS_BRIDGE */
Abstraction

#include "Implementor.h"

namespace NS_BRIDGE {

class Abstraction {
public:
	Abstraction(Implementor *imp) : _imp(imp) {}
	virtual ~Abstraction() {}
	virtual void operation(void)
	{
		_imp->operationImp();
	}

private:
	Implementor *_imp;
};

} /* namespace NS_BRIDGE */
main

#include "Bridge/Abstraction.h"
#include "Bridge/ConcreteImplementorA.h"
#include "Bridge/ConcreteImplementorB.h"
using namespace NS_BRIDGE;
int main(void)
{
	// 可以使用Abstract Factory创建实现
	// 如此以来这段代码将不依赖或需要知道任何实现
	ConcreteImplementorA ia;
	Abstraction abs(&ia);
	abs.operation();
}
附加:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值