设计模式之十八:桥接模式(Bridge)
Posted yxysuanfa
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式之十八:桥接模式(Bridge)相关的知识,希望对你有一定的参考价值。
桥接模式:
将抽象部分和它的实现部分相分离开来,以使它们能够单独地变化。
UML图:
主要包含:
- Abstraction:定义了抽象部分的接口。操作一个实现部分对象的引用。
- RefinedAbstraction:继承自抽象部分的类。
- Implementor:实现部分的接口。
- ConcreteImplementor:实现了Implementor定义的接口的详细类。
C++代码例如以下:
#include <iostream>
using namespace std;
class Implementor
{
public:
virtual void operationImpl()=0;
};
class ConcreteImplementorA:public Implementor
{
public:
void operationImpl()
{
cout<<"ConcreteImplementorA::operationImpl"<<endl;
}
};
class ConcreteImplementorB:public Implementor
{
public:
void operationImpl()
{
cout<<"ConcreteImplementorB::operationImpl"<<endl;
}
};
class Abstraction
{
public:
virtual void operation()=0;
void setImplementor(Implementor * i)
{
impl=i;
}
Implementor * getImplementor()
{
return impl;
}
protected:
Implementor * impl;
};
class RefinedAbstraction:public Abstraction
{
public:
void operation()
{
impl->operationImpl();
}
};
int main()
{
cout<<"桥接模式样例"<<endl;
Abstraction * ab=new RefinedAbstraction();
Implementor * cia=new ConcreteImplementorA();
ab->setImplementor(cia);
ab->operation();
Implementor * cib=new ConcreteImplementorB();
ab->setImplementor(cib);
ab->operation();
delete cia;
delete cib;
delete ab;
return 0;
}
运行输出:
以下是一个详细的样例,看这个详细的样例可能好理解一些,摘自大话设计模式:
- Abstraction为Phone(手机)。
- RefinedAbstraction为Samsung(三星手机)。Huawei(华为手机)。
- Implementor为Game(手机游戏)。
- ConcreteImplementor为NeedForSpeed(极品飞车)。QQGame(QQ游戏),FruitNinjia(水果忍者)。
UML类图为:
C++代码:
#include <iostream>
using namespace std;
class Game
{
public:
virtual void play()=0;
};
class NeedForSpeed :public Game
{
public:
virtual void play()
{
cout<<"need for speed play"<<endl;
}
};
class QQGame :public Game
{
public:
virtual void play()
{
cout<<"QQGame play"<<endl;
}
};
class FruitNinjia:public Game
{
public:
virtual void play()
{
cout<<"Fruit Ninjia play"<<endl;
}
};
class Phone
{
public:
virtual void run()=0;
void setGame(Game *g)
{
game=g;
}
Game * getGame()
{
return game;
}
protected:
Game *game;
};
class Samsung:public Phone
{
public:
virtual void run()
{
cout<<"Samsung :";
game->play();
}
};
class HuaWei:public Phone
{
public:
virtual void run()
{
cout<<"HuaWei :";
game->play();
}
};
int main()
{
cout<<"桥接模式真实的样例,不同的手机品牌和手机游戏"<<endl;
Phone *samsung=new Samsung();
Phone *huawei=new HuaWei();
Game * needForSpeed=new NeedForSpeed();
Game * qqGame=new QQGame();
Game * fruit=new FruitNinjia();
samsung->setGame(qqGame);
samsung->run();
huawei->setGame(needForSpeed);
huawei->run();
samsung->setGame(fruit);
samsung->run();
delete samsung;
delete huawei;
delete needForSpeed;
delete qqGame;
delete fruit;
return 0;
}
运行输出:
以上是关于设计模式之十八:桥接模式(Bridge)的主要内容,如果未能解决你的问题,请参考以下文章