//
// Bridge
// - Decouple an sbstraction from its implementation so that the two can
// vary independently.
//
// Author : ZAsia
// Date : 15/05/08
// Warning : In practice, declaration and implementation should
// be separated(.h and .cpp).
//
#include
using namespace std;
// Implementor
// - defines the interfaces for implementation classes. This interface doesn't
// have to correspond exactly to Abstraction's interface; in fact the two
// interfaces can be quite different. Typically the Implementor interface
// provides only primitive operations, and Abstraction defines higher-level
// operations based on these primitives.
class Implementor
{
public:
virtual void OperationImp() = 0;
};
// ConcreteImplementor
// - implements the Implementor interface and defines its concrete implementation.
class ConcreteImplementorA : public Implementor
{
public:
virtual void OperationImp()
{
cout << "ConcreteImplementorA::OperationImp..." << endl;
}
};
class ConcreteImplementorB : public Implementor
{
public:
virtual void OperationImp()
{
cout << "ConcreteImplementorB::OperationImp..." << endl;
}
};
// Abstraction
// - defines the abstraction's interface.
// - maintains a reference to an object of type Implementor.
class Abstraction
{
public:
Abstraction(Implementor *impl) : _impl(impl) { }
virtual void Operation() = 0;
protected:
Implementor *_impl;
};
// RefinedAbstraction
// - extends the interface defined by Abstraction.
class RefinedAbstraction : public Abstraction
{
public:
RefinedAbstraction(Implementor *impl) : Abstraction(impl) { }
void Operation() { _impl->OperationImp(); }
};
// Collaborations
// - Abstraction forwards client requests to its Implementor object
int main(int argc, char *argv[])
{
#define CONCRETE_IMPLEMENTOR_A
#ifdef CONCRETE_IMPLEMENTOR_A
Implementor *pImplObj = new ConcreteImplementorA();
#else
Implementor *pImplObj = new ConcreteImplementorB();
#endif
Abstraction *pAbsObj = new RefinedAbstraction(pImplObj);
pAbsObj->Operation();
if (pImplObj != nullptr)
{
delete pImplObj;
pImplObj = nullptr;
}
if (pAbsObj != nullptr)
{
delete pAbsObj;
pAbsObj = nullptr;
}
return 0;
}
///
// 1.Decoupling interface and implementation.
// An implementation is not bound permanently to an interface. The implementation
// of an abstraction can be configured at run-time. It's even possible for an
// object to change its implementation at run-time.
DesignPatterns_Bridge
最新推荐文章于 2021-12-29 22:15:08 发布