设计模式之适配器模式

适配器模式(Adapter pattern)属于结构型模式,如果想用一个接口去调用另一个类的功能,可以采用适配器模式,让适配器类来实现这个接口,在适配器内里调用另一类的功能,举个例子,有两种电源接线板,它们的功能是不一样的,两者的功能我们都想用,有一个可以直接插到插座上,插上就可用了,另外一个因为不能直接插,所以不能用,为了另外一个也能用,我们就需要一个转换插座,有了这个转换插座,这个不兼容的电源接线板也就能用了,这个转换插座就是适配器类。
下面是适配器模式的C++实现,代码可到本人github网页下载:设计模式例子

/*
 * Example of 'SingleTon' 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 CTarget
{
public:
    virtual void GeneralFunc()
    {
        cout<<"General function!"<<endl;
    };
};

class CAdaptee
{
public:
    void SpecialFunc()
    {
        cout<<"Special function!"<<endl;
    };
};

class CAdapter:public CTarget
{
public:
    CAdaptee* cp_adaptee;
public:
    CAdapter(CAdaptee* p_adaptee)
    {
        cp_adaptee=p_adaptee;
    };
public:
    void GeneralFunc()
    {
        cp_adaptee->SpecialFunc();  
    };
};

void main()
{
    CTarget* cp_target=new CTarget();
    CAdaptee* cp_adaptee=new CAdaptee();
    CTarget* cp_adapt=new CAdapter(cp_adaptee);
    cp_target->GeneralFunc();
    cp_adapt->GeneralFunc();
};

依据我们前面的比喻,CTarget就是其中的一类电源接线板,CAdaptee就是另外一种电源接线板,CAdapter就是转换头,有了这个转换头,我们就可用统一的接口用这两种接线板了,例如,其中的一个可以直接插到墙上,另外一个通过一个转接头也可以插到墙上用。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值