桥接模式

#include "stdafx.h"
#include <iostream>
using namespace std;
/*
桥接模式

定义:将抽象部分与它的实现部分分离,使它都可以独立的变化

解释(1):抽象与实现分离,并不是说,让抽象与其派生类分离,因为这没有任何意义。实际指的是抽象类和它的派生类用来实现自己的对象。
解释(2):实现系统可能有多角度分类,每一种分类都有可能变化,那么就把这种多角度分离出来让它们独立变化,减少它们之间的耦合。

个人理解:由于一个实现需要多个不同类型的角色组成,并且这些角色的实现都是变动的。
若是整个实现都通过继承来架构多个角色之间的关系,存在的问题是要破坏开闭原则,且扩展时会有大量的变动。
桥接模式的结构,可以理解为选择一种合适的角色作为抽象类,在抽象类中将其他角色通过聚合的方式,以此降低角色变动之间的耦合度。

组成:
(1)抽象类
(2)从抽象类派生的被提炼的实现类
(3)角色抽象类
(4)从角色抽象类中派生的各个不同的角色的实现类
*/


class Implementor{
public:
	virtual void operationImp() = 0;

};

class ImplementorA : public Implementor
{
public:
	virtual void operationImp(){cout<<"ImplementorA->operationImp"<<endl;}

protected:
private:
};

class ImplementorB : public Implementor
{
public:
	virtual void operationImp(){cout<<"ImplementorB->operationImp"<<endl;}
protected:
private:
};


class Abstract
{
public:	
	virtual void operation(){cout<<"Abstract->operation"<<endl;
	m_pImplementor->operationImp();}
	virtual void setImplementor(Implementor *pImplementor){this->m_pImplementor = pImplementor;}	
protected:
	Implementor *m_pImplementor;
private:
};

class RefinedAbstract : public Abstract
{
public:
	virtual void operation(){cout<<"RefinedAbstract->operation"<<endl;
	m_pImplementor->operationImp();}
protected:
private:
};


/*
//例如扩展,imp角色添加一种新的模式,且refiend添加新的模式

class RefinedAbstractA : public Abstract
{
public:
	virtual void operation(){cout<<"RefinedAbstractA->operation"<<endl;
	m_pImplementor->operationImp();}
protected:
private:
};

class ImplementorC : public Implementor
{
public:
	virtual void operationImp(){cout<<"ImplementorC->operationImp"<<endl;}
protected:
private:
};
*/


int _tmain(int argc, _TCHAR* argv[])
{

	Implementor *pIA = new ImplementorA();
	Implementor *pIB = new ImplementorB();
	


	Abstract * pAb = new RefinedAbstract();
	pAb->setImplementor(pIA);
	pAb->operation();

	pAb->setImplementor(pIB);
	pAb->operation();


//
/*
	//对新添加的模式调用
	Implementor *pIC = new ImplementorC();
	Abstract * pAbA = new RefinedAbstractA();
	pAbA->setImplementor(pIA);
	pAbA->operation();

	pAbA->setImplementor(pIB);
	pAbA->operation();

	pAbA->setImplementor(pIC);
	pAbA->operation();
	delete pAbA; pAbA = NULL;
	delete pIC;pIC = NULL;
	*/



	delete pAb; pAb = NULL;
	
	delete pIA; pIA = NULL;
	delete pIB;pIB = NULL;
	

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值