设计模式之桥接模式

桥接模式(Bridge)属于结构模式,桥接模式提供了一种灵活应对变化的方法,它通过把抽象类和它的实现这种上下的耦合关系转换成聚合的关系,也就是具体实现是独立实现的,而抽象类拥有对它的引用,这样,如果需要扩充实现类的功能,这个时候又不能违背单一职责准则,则只需要在抽象类的实现里面增加新的功能即可。
下面是桥接模式的C++实现,代码可到本人github网页下载:设计模式例子

/*
 * Example of 'Bridge' design pattern.
 * Copyright (C) 2016 Leo Wang
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#include <iostream>
using namespace std;

class CImplement
{
    public:
        virtual void GeneralFunc()=0;
};

class CConcreteImplementA:public CImplement
{
    public:
        void GeneralFunc()
        {
            cout<<"General func type A!"<<endl;
        };
};

class CConcreteImplementB:public CImplement
{
    public:
        void GeneralFunc()
        {
            cout<<"General func type B!"<<endl;
        };
};

class CAbstract
{
    public:
        CImplement* cp_impl;
    public:
        virtual void SpecialFunc()=0;
    public:
        CAbstract(CImplement* p_impl)
        {
            cp_impl=p_impl;
        };
};

class CConcreteAbstract:public CAbstract
{
    public:
        void SpecialFunc()
        {
            cout<<"Special func!"<<endl;
            cp_impl->GeneralFunc();
        }
    public:
        CConcreteAbstract(CImplement* p_impl):CAbstract(p_impl)
    {};
};

int main()
{
    CImplement* cp_impA=new CConcreteImplementA();
    CImplement* cp_impB=new CConcreteImplementB();
    CAbstract* cp_abstractA=new CConcreteAbstract(cp_impA);
    CAbstract* cp_abstractB=new CConcreteAbstract(cp_impB);
    cp_impA->GeneralFunc();
    cp_impB->GeneralFunc();
    cp_abstractA->SpecialFunc();
    cp_abstractB->SpecialFunc();
    return 1;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值