Bridge模式

意图:将一组实现与另一组使用它的对象分离,可解决抽象类的派生类需要使用多个实现,而不出现类爆炸性增长的问题。

问题:现有三种射门技术: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;
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值