设计模式-第十八章-桥接模式

一、UML图 

二、包含的角色

Implementor类,实现部分抽象出来的接口。

ConcreteImplementorA,ConcreteImplementorB为Implement派生的类,为具体的实现。

Abstraction类,抽象部分实现。

RefinedAbstraction类,提炼出来的抽象部分。

三、特点

桥接模式(Bridge),将抽象部分与它的实现部分分离,使它们都可以独立地变化。

这里并不是说,让抽象类与派生类分离,而是指,抽象类和它的派生类用来实现自己的对象。

实现系统可能有多角度分类,每一种分类都有可能变化。那么就把这种多角度分离出来,让它们独立变化,减少耦合。

四、代码实现

Implementor类

class Implementor
{
public:
    virtual ~Implementor() {}
    virtual void Operation() = 0;
};

ConcreteImplementorA和ConcreteImplementorB类

#pragma once
#include "Implementor.h"
#include <iostream>

using namespace std;
class ConcreteImplementorA : public Implementor {
    public:
        ConcreteImplementorA () {}
        virtual void Operation() override
        {
            cout << "|" << "具体实现A的方法执行" << "|" << endl;
        }    
};

class ConcreteImplementorB : public Implementor {
    public:
        ConcreteImplementorB () {}
        virtual void Operation() override
        {
            cout << "|" << "具体实现B的方法执行" << "|" << endl;
        }    
};

Abstraction类

#pragma once
#include "Implementor.h"
class Abstraction
{
public:
    virtual ~Abstraction() {}
    Abstraction() {}
    virtual void Operation()
    {
        _implementor->Operation();
    }
    
    void SetImplementor(Implementor *impl)
    {
        _implementor =impl;
    }

private:
    Implementor *_implementor;
};

RefinedAbstraction类

#pragma once
#include "Abstraction.h"
#include <iostream>

using namespace std;

class RefinedAbstraction : public Abstraction
{

public:
    void Operation()
    {
        cout << "|" << "RefinedAbstraction 方法" << "|" << endl << "->>>";
        Abstraction::Operation();
    }
};

调用方法

#include "Abstraction.h"
#include "Implementor.h"
#include "ConcreteImplementorA.h"
#include "ConcreteImplementorB.h"
#include "RefinedAbstraction.h"

#include <memory>

int main(int argc, char **argv)
{
    std::shared_ptr<Implementor> implA(new ConcreteImplementorA());
    std::shared_ptr<Implementor> implB(new ConcreteImplementorB());


    std::shared_ptr<Abstraction> d1(new Abstraction());
    d1->SetImplementor(implA.get());

    std::shared_ptr<Abstraction> d2(new RefinedAbstraction());
    d2->SetImplementor(implA.get());
    std::shared_ptr<Abstraction> d3(new RefinedAbstraction());
    d3->SetImplementor(implB.get());

    d1->Operation();
    d2->Operation();
    d3->Operation();

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值