桥接模式

桥接模式

大家好,又见面了,我是全栈君,今天给大家准备了Idea注册码。

桥接模式是一种结构模式,在软件系统,某些类型的,因为它自己的逻辑。它具有变化的二维或更多维,使用的桥型可以很容易地进行修改的类型可以在多个方向上进行,而不会引入额外的复杂性。

桥梁模式的用意是”将抽象化(Abstraction)与实现化(Implementation)脱耦,使得二者能够独立地变化”,。桥接模式把依赖详细实现,提升为依赖抽象。来完毕对象和变化因素之间的低耦合,提高系统的可维护性和扩展性。

桥接模式的主要目的是将一个对象的变化与其他变化隔离开,让彼此之间的耦合度最低。

UML类图:

桥接模式

桥接模式中涉及到以下几个角色:

Abstraction类:定义了抽象类的接口,而且包括一个指向抽象类implementor的指针,在须要不同的实现方式的时候,仅仅须要传入不同的实现类的指针就能够了。

RefineAbstraction类:扩充Abstraction类的接口

Implementor类:定义实现类的接口,实现类被Abstraction以组合方式

ConcreteImplementor:实现Implementor类的接口,普通情况下有多个详细的类

C++实现代码例如以下:

class Abstration //抽象类定义接口
	{
	public:
		Abstration(Implementor* imp) :mImp(imp){}
		virtual ~Abstration(){}
		virtual void operation() = 0;
	protected:
		Implementor *mImp;	//使用组合的方式,实现了低耦合
	};
	class ReDefineAbstration :public Abstration		//
	{
	public:
		ReDefineAbstration(Implementor* imp) :Abstration(imp){}
		~ReDefineAbstration(){}
		void operation()
		{
			mImp->operationImplementor();
		}
	};
	class Implementor	//实现类的抽象基类
	{
	public:
		Implementor(){}
		virtual ~Implementor(){}
		virtual void operationImplementor() = 0;
	};
	class ConcreteImpelmentorA :public Implementor	//详细的实现类A
	{
	public:
		ConcreteImpelmentorA(){}
		~ConcreteImpelmentorA(){}
		void operationImplementor()
		{
			cout << "ConcreteImpelmentorA implements this interface" << endl;
		}
	};
	class ConcreteImpelmentorB :public Implementor	//详细的实现类B
	{
	public:
		ConcreteImpelmentorB(){}
		~ConcreteImpelmentorB(){}
		void operationImplementor()
		{
			cout << "ConcreteImpelmentorB implements this interface" << endl;
		}
	};
	void test()
	{
		Implementor *pImpA = new ConcreteImpelmentorA();
		Implementor *pImpB = new ConcreteImpelmentorB();
		Abstration *abstA = new ReDefineAbstration(pImpA);
		Abstration *abstB = new ReDefineAbstration(pImpB);
		abstA->operation();
		abstB->operation();
		delete pImpA;
		delete pImpB;
		delete abstA;
		delete abstB;
	}


桥接模式使得抽象和实现分离。在不同的类中定义。抽象接口类使用低耦合的组合方式包括了实现类,大大提高了系统的扩展性和维护性。


版权声明:本文博客原创文章,博客,未经同意,不得转载。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/117645.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)
blank

相关推荐

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号