桥接模式:
将抽象部分和它的实现部分相分离开来,以使它们可以单独地变化。
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;
}
执行输出:
时间: 2024-10-21 17:02:18