zoukankan      html  css  js  c++  java
  • 桥接模式

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

    桥梁模式的用意是"将抽象化(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;
    	}

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


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

  • 相关阅读:
    2019 icpc南昌全国邀请赛-网络选拔赛J题 树链剖分+离线询问
    Android小项目之十二 设置中心的界面
    【Mood-5】14条建议,使你的IT职业生涯更上一层楼
    【Android 界面效果15】Android UI 之一步步教你自定义控件(自定义属性、合理设计onMeasure、合理设计onDraw等)
    单线程模型中Message、Handler、Message Queue、Looper之间的关系
    140个google面试题
    Android小项目之十一 应用程序的主界面
    Android小项目之十 应用程序更新的签名问题
    Android小项目之九 两种上下文的区别
    Android小项目之八 界面细节
  • 原文地址:https://www.cnblogs.com/yxwkf/p/4623617.html
Copyright © 2011-2022 走看看