Bridge模式
在面向对象的开发过程中,要做到2点:1.高内聚 2.松耦合.但是在实际开发过程中难以把握,例如会遇到这样的问题:
1)客户给了一个需求,之后我们用一个类A来实现.
2)客户的需求有了变化,要用到2个算法来实现.于是我们通过定义一个抽象基类A,再用两个具体类A1和A2实现这两个算法.
3)客户需求又有了变化,要求在2个操作系统上实现.我们再抽象一个层次,不同操作系统抽象为A0和A1,每个操作系统上有2个算法,实现为A00,A01和A10,A11,总共有4个类.
4)客户需求如果再有变化,那么我们又要重新设计.
Bridge(桥接)模式正是解决这个问题的.Bridge模式的核心在于将抽象部分和实现分离,它们两者可以独立地变化.
它的类结构图如下:
下面是实现的代码
//Abstraction.h
//Abstraction.h
#ifndef _ABSTRACTION_H_
#define _ABSTRACTION_H_
class AbstractionImp;
class Abstraction
{
public:
virtual ~Abstraction();
virtual void Operation() = 0 ;
protected:
Abstraction();
};
class RefinedAbstraction :public Abstraction
{
public:
RefinedAbstraction(AbstractionImp* imp);
~RefinedAbstraction();
void Operation() ;
private:
AbstractionImp* _imp;
};
#endif
//Abstraction.cpp
#include"Abstraction.h"
#include"AbstractionImp.h"
Abstraction::Abstraction()
{
}
Abstraction::~Abstraction()
{
}
RefinedAbstraction::RefinedAbstraction(AbstractionImp* imp)
{
_imp = imp;
}
RefinedAbstraction::~RefinedAbstraction()
{
}
void RefinedAbstraction::Operation()
{
_imp->Operation();
}
//AbstractionImp.h
//AbstractionImp.h
#ifndef _ABSTRACTIONIMP_H_
#define _ABSTRACTIONIMP_H_
class AbstractionImp
{
public:
virtual ~AbstractionImp();
virtual void Operation() = 0;
protected:
AbstractionImp();
};
class ConcreteAbstractionImpA :public AbstractionImp
{
public:
ConcreteAbstractionImpA();
~ConcreteAbstractionImpA();
virtual void Operation();
};
class ConcreteAbstractionImpB :public AbstractionImp
{
public:
ConcreteAbstractionImpB();
~ConcreteAbstractionImpB();
virtual void Operation();
};
#endif
//AbstractionImp.cpp
#include"AbstractionImp.h"
#include<iostream>
using namespace std;
AbstractionImp::AbstractionImp()
{
}
AbstractionImp::~AbstractionImp()
{
}
ConcreteAbstractionImpA::ConcreteAbstractionImpA()
{
}
ConcreteAbstractionImpA::~ConcreteAbstractionImpA()
{
}
void ConcreteAbstractionImpA::Operation()
{
cout << "ConcreteAbstractionImpA Operation" << endl;
}
ConcreteAbstractionImpB::ConcreteAbstractionImpB()
{
}
ConcreteAbstractionImpB::~ConcreteAbstractionImpB()
{
}
void ConcreteAbstractionImpB::Operation()
{
cout << "ConcreteAbstractionImpB Operation" << endl;
}
//main.cpp
#include"Abstraction.h"
#include"AbstractionImp.h"
int main()
{
AbstractionImp* impA = new ConcreteAbstractionImpA();
AbstractionImp* impB = new ConcreteAbstractionImpB();
Abstraction* absA = new RefinedAbstraction(impA);
Abstraction* absB = new RefinedAbstraction(impB);
absA->Operation();
absB->Operation();
return 0;
}