蜗牛的家
男儿当自强
posts - 48,  comments - 21,  trackbacks - 0

意图:
将抽象部分与它的实现部分分离,使它们都可以独立的变化
适用:
你不希望在抽象和它的实现部分之间有一个固定的绑定关系。例如这种情况可能是因为,在程序运行时刻实现部分应可以被选择或是切换
类的抽象以及它的实现都应该可以通过生成子类的方法加以扩充。这时Bridge模式使你可以对不同的抽象接口和实现部分进行组合,并分别对他们进行扩充
对一个抽象的实现部分的修改应对客户不产生影响,即客户的代码不必重新编译
你相对客户完全隐藏抽象的实现部分
有许多类要生成,这样一种类层次结构说明你必须将一个对象分解成两个部分
你想在多个对象间共享实现,但同时要求客户并不知道这一点,一个简单的例子便是String类
UML图

解析:
Bridge的实现方式跟Builde十分相似,只是封装的东西不同。Builder封装了不同的生成部分(构造)idge封装了不同的实现方式(函数)

//test.h
//////////////////////////////////////////////////////////////////////////
class Implementor;

class Abstraction
{
public:
    Abstraction(Implementor
* pImplementor);
    
virtual ~Abstraction();

    
void Opertion();

protected:
    Implementor
* m_pImplementor;
}
;

//抽象基类,定义了实现的接口函数
class Implementor
{
public:
    Implementor()
{}
    
virtual ~Implementor(){}

    
virtual void OpertionImpl() = 0;
}
;

//两种不同的实现
class ConCreateImplementorA : public Implementor
{
public:
    ConCreateImplementorA()
{}
    
virtual ~ConCreateImplementorA(){}

    
virtual void OpertionImpl();
}
;

class ConCreateImplementorB : public Implementor
{
public:
    ConCreateImplementorB()
{}
    
virtual ~ConCreateImplementorB(){}

    
virtual void OpertionImpl();
}
;


 

// test.cpp : Defines the entry point for the console application.
//

#include 
"stdafx.h"
#include 
<iostream>
#include 
"stdlib.h"
#include 
"test.h"

using namespace std;
//////////////////////////////////////////////////////////////////////////
void ConCreateImplementorA::OpertionImpl()
{
    cout 
<< "Implementation by ConcreateImplementorA\n";
}


void ConCreateImplementorB::OpertionImpl()
{
    cout 
<< "Implementation by ConcreateImplementorB\n";
}


Abstraction::Abstraction(Implementor
* pImplementor) : m_pImplementor(pImplementor)
{
}


Abstraction::
~Abstraction()
{
    delete m_pImplementor;
    m_pImplementor 
= NULL;
}


void Abstraction::Opertion()
{
    m_pImplementor
->OpertionImpl();
}


//////////////////////////////////////////////////////////////////////////
int main(int argc, char* argv[])
{
    ConCreateImplementorA 
*pImplA = new ConCreateImplementorA;
    Abstraction 
*pAbstraction1 = new Abstraction(pImplA);
    pAbstraction1
->Opertion();

    ConCreateImplementorB 
*pImplB = new ConCreateImplementorB;
    Abstraction 
*pAbstraction2 = new Abstraction(pImplB);
    pAbstraction2
->Opertion();

    delete pAbstraction1;
    delete pAbstraction2;
    
    system(
"pause");
    
return 0;
}


 

posted on 2008-08-17 23:11 黑色天使 阅读(337) 评论(0)  编辑 收藏 引用 所属分类: 设计模式

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理



<2008年8月>
272829303112
3456789
10111213141516
17181920212223
24252627282930
31123456

常用链接

留言簿(2)

随笔分类

随笔档案

文章档案

搜索

  •  

最新评论

阅读排行榜

评论排行榜