设计模式读书笔记:Bridge(桥接)
2015-07-10 15:53:47
意图:
将抽象部分与它的实现部分分离,使它们都可以独立地变化。
结构图:来自 《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();
}
附加: