设计模式(3)--对象结构(2)--桥接

1. 意图

    将抽象部分与它的实现部分分离,使它们都可以独立地变化。

2. 四种角色

    抽象(Abstraction)、细化抽象(Refined Abstraction)、抽象实现者(Implementor)、具体实现者(Concrete Implementor)

3. 优点

    3.1 分离接口及其实现部分

    3.2 提高可扩充性

    3.3 实现细节对客户透明

4. 缺点

    N/A

5. 相关模式

    5.1 抽象工厂可以用来创建和配置一个特定的Bridge模式。

    5.2 适配器模式用来帮助无关的类协同工作,通常在系统完成后(类已经设计好)才使用,

           而桥接模式在系统开始时(设计类之前)就被使用。

6. 代码示意(C++)
#pragma once
#include <iostream>
using namespace std;

class Implementor
{
public:
	virtual void OperationImp() = 0;//基本操作
};
class ConcreteImplementorA : public Implementor
{
public:
	virtual void OperationImp() 
	{
		cout << "ConcreteImplementorA:OperationImp" << endl;
	}
};
class ConcreteImplementorB : public Implementor
{
public:
	virtual void OperationImp()
	{
		cout << "ConcreteImplementorB:OperationImp" << endl;
	}
};

class ImplementorFactory
{
private:
	static ImplementorFactory* s_singleton;
private:
	ImplementorFactory(){}
public:
	static ImplementorFactory* Instance() 
	{
		if (s_singleton == 0)
		{
			s_singleton = new ImplementorFactory;
		}
		return s_singleton;
	}
public:
	Implementor* MakeImplementor(int type)
	{
		if (1 == type)
		{
			return new ConcreteImplementorA;
		}
		else
		{
			return new ConcreteImplementorB;
		}
	}
};

class Abstraction
{
protected:
	Implementor* m_pImplementor;
	int m_type;
public:
	Abstraction() 
	{
		m_pImplementor = 0;
		m_type = 0;
	}
	~Abstraction() 
	{
		delete m_pImplementor;
	}
	virtual void Operation()
	{
		//Operation可以由多个基本操作组合
		//例如可以多次调用OperationImp
		GetImplementor()->OperationImp();
		GetImplementor()->OperationImp();
	}
protected:
	Implementor* GetImplementor()
	{   //从单例工厂里获取Implementor
		return ImplementorFactory::Instance()->MakeImplementor(m_type);
	}
};
class RefinedAbstraction1 : public Abstraction
{
public:
	RefinedAbstraction1()
	{
		m_type = 1;
	}
};
class RefinedAbstraction2 : public Abstraction
{
public:
	RefinedAbstraction2()
	{
		m_type = 2;
	}

};

Bridge.cpp:

#include "Bridge.h"

ImplementorFactory* ImplementorFactory::s_singleton = 0;
#include "Bridge.h"
int main() 
{
	Abstraction* pAbstraction = new RefinedAbstraction1;
	pAbstraction->Operation();
	delete pAbstraction;

	pAbstraction = new RefinedAbstraction2;
	pAbstraction->Operation();
	delete pAbstraction;

	return 0;
}

运行结果:

6.1 接口Abstraction和实现Implementor分离,接口类维护一个实现类的指针(3.1)

6.2 可以单独对Abstraction或Implementor扩充(生成新的子类)(3.2)

6.3 使用了单例的工厂来生成Implementor

 

  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值