首页 > 代码库 > Bridge 模式

Bridge 模式

Bridge 模式将抽象和行为划分开来,各自独立,但能动态的结合。在面向对象设计的基本概念中,对象这个概念实际是由属性和行为两个部分组成的,属性我们可以认为是一种静止的,是一种抽象,一般情况下,行为是包含在一个对象中,但是,在有的情况下,我们需要将这些行为也进行归类,形成一个总的行为接口,这就是桥模式的用处。

 1 ///////////////Abstraction.h/////////////
 2 #pragma once
 3 class AbstractionImp ;
 4 class Abstraction
 5 {
 6 public:
 7     virtual ~Abstraction();
 8     virtual void Operation() = 0 ;
 9 protected:
10     Abstraction();
11 private:
12 };
13 
14 class RefinedAbstraction : public Abstraction
15 {
16 public:
17     ~RefinedAbstraction();
18     RefinedAbstraction();
19     RefinedAbstraction(AbstractionImp* imp);
20     void Operation();
21 protected:
22 private:
23     AbstractionImp* _imp ;
24 };
///////////////Abstraction.cpp/////////////
#include "Abstraction.h"
#include "AbstractionImp.h"
Abstraction::~Abstraction()
{

}
Abstraction::Abstraction()
{

}
void Abstraction::Operation()
{

}

RefinedAbstraction::~RefinedAbstraction()
{

}
RefinedAbstraction::RefinedAbstraction()
{

}
RefinedAbstraction::RefinedAbstraction(AbstractionImp* imp)
{
    _imp = imp ;
}
void RefinedAbstraction::Operation()
{
    _imp->Operation();
}
 1 ///////////////AbstractionImp.h/////////////
 2 #pragma once
 3 class AbstractionImp
 4 {
 5 public:
 6     virtual ~AbstractionImp();
 7     virtual void Operation() = 0;
 8 
 9 protected:
10     AbstractionImp();
11 private:
12 };
13 
14 class ConcreteAbstractionImpA : public AbstractionImp
15 {
16 public:
17     ~ConcreteAbstractionImpA();
18     ConcreteAbstractionImpA();
19     void Operation();
20 protected:
21 private:
22 };
23 
24 class ConcreteAbstractionImpB : public AbstractionImp
25 {
26 public:
27     ~ConcreteAbstractionImpB();
28     ConcreteAbstractionImpB();
29     void Operation();
30 protected:
31 private:
32 };
 1 ///////////////AbstractionImp.cpp/////////////
 2 #include "AbstractionImp.h"
 3 #include <iostream>
 4 using namespace std;
 5 AbstractionImp::~AbstractionImp()
 6 {
 7 
 8 }
 9 AbstractionImp::AbstractionImp()
10 {
11 
12 }
13 void AbstractionImp::Operation()
14 {
15 
16 }
17 ConcreteAbstractionImpA::~ConcreteAbstractionImpA()
18 {
19 
20 }
21 ConcreteAbstractionImpA::ConcreteAbstractionImpA()
22 {
23 
24 }
25 void ConcreteAbstractionImpA::Operation()
26 {
27     cout<<"ConcreteAbstractionImpA...."<<endl; 
28 }
29 
30 
31 ConcreteAbstractionImpB::~ConcreteAbstractionImpB()
32 {
33 
34 }
35 ConcreteAbstractionImpB::ConcreteAbstractionImpB()
36 {
37 
38 }
39 void ConcreteAbstractionImpB::Operation()
40 {
41     cout<<"ConcreteAbstractionImpB...."<<endl; 
42 }
 1 ///////////////main.cpp/////////////
 2 #include "Abstraction.h"
 3 #include "AbstractionImp.h"
 4 #include <iostream>
 5 using namespace std ;
 6 int main()
 7 {
 8     AbstractionImp* impA = new ConcreteAbstractionImpA();
 9     Abstraction* abs = new RefinedAbstraction(impA);
10     abs->Operation();
11     system("pause");
12     return 0;
13 }