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

    桥接模式Bridge):

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



        需要解释一下,什么叫做抽象与它的实现分离,这并不是说,让抽象类与其派生类分离,这没有任何意义。实现指的是抽象类和它的派生类用来实现自己的对象。也就是说手机既可以按照品牌分类又可以按照功能分类。


        由于实现的方式有多种,桥接模式的核心意图就是把这些实现独立出来,让他们各自的变化,这就使得每种实现的变化不会影响其他实现,从而达到应对变化的目的。

    桥接模式代码:

    #pragma once
    #include <string>
    #include <iostream>
    using namespace std;
    
    //implementor
    class CImplementor
    {
    public:
    	virtual void Operation() = 0;
    };
    
    //ConcreteImplementorA,ConcreteImplementorB
    class CConcreteImplementorA : public CImplementor
    {
    public:
    	void Operation()
    	{
    		cout<<"Execution method A"<<endl;
    	}
    };
    class CConcreteImplementorB : public CImplementor
    {
    public:
    	void Operation()
    	{
    		cout<<"Execution method B"<<endl;
    	}
    };
    
    //Abstraction
    class CAbstraction
    {
    protected:
    	CImplementor *m_pImplementor;
    public:
    	CAbstraction(){m_pImplementor = NULL;}
    	void SetImplementor(CImplementor *pImplementor)
    	{
    		m_pImplementor = pImplementor;
    	}
    	virtual void Operation() = 0;
    };
    
    //RefinedAbstraction
    class CRefinedAbstraction : public CAbstraction
    {
    public:
    	void Operation()
    	{
    		if(m_pImplementor != NULL)
    		{
    			m_pImplementor->Operation();
    		}
    	}
    };
    客户端调用代码:

    #include "stdafx.h"
    #include "BridgeMode.h"
    using namespace std;
    
    int main()
    {
    	CAbstraction *pAb = new CRefinedAbstraction();
    	CConcreteImplementorA *pcA = new CConcreteImplementorA();
    	CConcreteImplementorB *pcB = new CConcreteImplementorB();
    	pAb->SetImplementor(pcA);
    	pAb->Operation();
    	pAb->SetImplementor(pcB);
    	pAb->Operation();
    
    	delete pAb;
    	delete pcA;
    	delete pcB;
    	return 0;
    }
    
    执行结果:
    总结:
        实现系统可能有多角度分类,每一种分类都有可能变化,那么就把这种多角度分离出来让它们独立变化,减少它们之间的耦合。
  • 相关阅读:
    uva 11294 Wedding
    uvalive 4452 The Ministers’ Major Mess
    uvalive 3211 Now Or Later
    uvalive 3713 Astronauts
    uvalive 4288 Cat Vs. Dog
    uvalive 3276 The Great Wall Game
    uva 1411 Ants
    uva 11383 Golden Tiger Claw
    uva 11419 SAM I AM
    uvalive 3415 Guardian Of Decency
  • 原文地址:https://www.cnblogs.com/csnd/p/12062327.html
Copyright © 2011-2022 走看看