• 设计模式-桥接模式


    桥接模式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;
    }
    
    执行结果:
    总结:
        实现系统可能有多角度分类,每一种分类都有可能变化,那么就把这种多角度分离出来让它们独立变化,减少它们之间的耦合。
  • 相关阅读:
    【CODEVS1380】没有上司的舞会
    【poj2248】Addition Chains
    【poj3070】Fibonacci
    【NOIP2006】开心的金明
    【Tyvj1359】收入计划
    【NOIP2015】跳石头
    【CODEVS1219】骑士游历
    暑假假期总结第六周
    暑假假期总结第五周
    暑假假期总结第四周
  • 原文地址:https://www.cnblogs.com/csnd/p/12062328.html
Copyright © 2020-2023  润新知