意图:将一组实现与另一组使用它的对象分离,可解决抽象类的派生类需要使用多个实现,而不出现类爆炸性增长的问题。
问题:现有三种射门技术:DalichousheImplementor(大力抽射)、YuanyuewandaoImplementor(圆月弯刀)、DiantiqiuImplementor(电梯球),每个球员都可以学习到其中一种技术并能用之射门。
这里,每种射门技术,就是一种具体的实现,而每个具体的球员,就是使用的对象,如果只是简单滴地,硬编码每个具体球员拥有的技术,则当需要更改该球员拥有的技术时,就会出现类爆炸性增加情况。如果使用Brideg模式,则可避免。
实现关键:球员抽象类里有射门技术的implementor
代码:
ShootImplementor.h
#ifndef _BRIDGE_SHOOTIMPLEMENTOR_H_
#define _BRIDGE_SHOOTIMPLEMENTOR_H_
#include <iostream>
class ShootImplementor
{
public:
ShootImplementor(){}
~ShootImplementor(){}
virtual void shoot() = 0;
};
class DalichousheImplementor : public ShootImplementor
{
public:
static DalichousheImplementor* instance();
~DalichousheImplementor();
virtual void shoot();
private:
DalichousheImplementor(){}
static DalichousheImplementor* _inst;
};
class YuanyuewandaoImplementor : public ShootImplementor
{
public:
static YuanyuewandaoImplementor* instance();
~YuanyuewandaoImplementor();
virtual void shoot();
private:
YuanyuewandaoImplementor(){}
static YuanyuewandaoImplementor* _inst;
};
class DiantiqiuImplementor : public ShootImplementor
{
public:
static DiantiqiuImplementor* instance();
~DiantiqiuImplementor();
virtual void shoot();
private:
DiantiqiuImplementor(){}
static DiantiqiuImplementor* _inst;
};
#endif
Player.h
#ifndef _BRIDGE_PLAYERABSTRACTION_H_
#define _BRIDGE_PLAYERABSTRACTION_H_
#include "ShootImplementor.h"
class Player
{
public:
Player( ShootImplementor* shootSkill ){ _shootSkill = shootSkill; }
~Player(){}
virtual void shoot() = 0;
ShootImplementor* _shootSkill;
};
class MidField : public Player
{
public:
MidField( ShootImplementor* shootSkill ):Player(shootSkill){ }
~MidField(){}
virtual void shoot();
};
class Striker : public Player
{
public:
Striker( ShootImplementor* shootSkill ):Player(shootSkill){ }
~Striker(){}
virtual void shoot();
};
class Back : public Player
{
public:
Back( ShootImplementor* shootSkill ):Player(shootSkill){ }
~Back(){}
virtual void shoot();
};
#endif
main.cpp
/*********************************************
*情境:现在有3种射门技巧,每个球员只能学习到一种。若要增加射门技巧或者增加球员的种类,可考虑Bridge模式。分析可变性,射门技巧和球员
*为变化,将变化封装,抽象和实现解耦。
*Bridge模式
*意图:将一组实现与另一组使用它们的对象分离
**********************************************/
#include "PlayerAbstraction.h"
#include "ShootImplementor.h"
int main( int argc, char** argv )
{
MidField messi( YuanyuewandaoImplementor::instance() );
Striker neymar( DiantiqiuImplementor::instance() );
Back mascherano( DalichousheImplementor::instance() );
messi.shoot();
neymar.shoot();
mascherano.shoot();
return 0;
}