标签:通过 ring int variable cout parent ble split include
在面向对象的开发过程中,要做到2点:1、高内聚(cohesion)。2、松耦合(coupling)。可是在实际开发过程中难以把握,比如会遇到这种问题:
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;
}
标签:通过 ring int variable cout parent ble split include
原文地址:http://www.cnblogs.com/cxchanpin/p/7077798.html