zoukankan      html  css  js  c++  java
  • 设计模式---适配器模式

    一、定义

    适配器模式:将一个类的借口,转换成客户期望的另一个接口。适配器让原本接口不兼容的类可以合作无间。

    二、模式结构

    适配器模式包含如下角色:

    • Target:目标抽象类
    • Adapter:适配器类
    • Adaptee:适配者类
    • Client:客户类

    适配器模式有对象适配器和类适配器两种实现:

    对象适配器:

    类适配器:

    三、代码样例

    #include <iostream>
    #include "Adapter.h"
    #include "Adaptee.h"
    #include "Target.h"
    
    using namespace std;
    
    int main(int argc, char *argv[])
    {
        Adaptee * adaptee  = new Adaptee();
        Target * tar = new Adapter(adaptee);
        tar->request();
        
        return 0;
    }
    ///////////////////////////////////////////////////////////
    //  Adapter.h
    //  Implementation of the Class Adapter
    //  Created on:      03-十月-2014 17:32:00
    //  Original author: colin
    ///////////////////////////////////////////////////////////
    
    #if !defined(EA_BD766D47_0C69_4131_B7B9_21DF78B1E80D__INCLUDED_)
    #define EA_BD766D47_0C69_4131_B7B9_21DF78B1E80D__INCLUDED_
    
    #include "Target.h"
    #include "Adaptee.h"
    
    class Adapter : public Target
    {
    
    public:
        Adapter(Adaptee *adaptee);
        virtual ~Adapter();
    
        virtual void request();
    
    private:
        Adaptee* m_pAdaptee;
    
    };
    #endif // !defined(EA_BD766D47_0C69_4131_B7B9_21DF78B1E80D__INCLUDED_)
    ///////////////////////////////////////////////////////////
    //  Adapter.cpp
    //  Implementation of the Class Adapter
    //  Created on:      03-十月-2014 17:32:00
    //  Original author: colin
    ///////////////////////////////////////////////////////////
    
    #include "Adapter.h"
    
    Adapter::Adapter(Adaptee * adaptee){
        m_pAdaptee =  adaptee;
    }
    
    Adapter::~Adapter(){
    
    }
    
    void Adapter::request(){
        m_pAdaptee->specificRequest();
    }
    ///////////////////////////////////////////////////////////
    //  Adaptee.h
    //  Implementation of the Class Adaptee
    //  Created on:      03-十月-2014 17:32:00
    //  Original author: colin
    ///////////////////////////////////////////////////////////
    
    #if !defined(EA_826E6B4F_12BE_4609_A0A3_95BD5E657D36__INCLUDED_)
    #define EA_826E6B4F_12BE_4609_A0A3_95BD5E657D36__INCLUDED_
    
    class Adaptee
    {
    
    public:
        Adaptee();
        virtual ~Adaptee();
    
        void specificRequest();
    
    };
    #endif // !defined(EA_826E6B4F_12BE_4609_A0A3_95BD5E657D36__INCLUDED_)

     运行结果:

  • 相关阅读:
    记一次JAVA WEB项目解决XSS攻击的办法(亲测有效)
    常用oracle可重复执行的脚本模板
    mybatis配置文件查询参数的传递
    oracle xmltype导入并解析Excel数据 (五)中间表数据入库
    oracle xmltype导入并解析Excel数据 (四)特别说明
    oracle xmltype导入并解析Excel数据 (三)解析Excel数据
    oracle xmltype导入并解析Excel数据 (二)规则说明
    oracle xmltype导入并解析Excel数据 (一)创建表与序
    ipv4,ipv6起止地址判断,网段判断
    HTML li标签排列有空白间隙
  • 原文地址:https://www.cnblogs.com/zhanghu52030/p/9598095.html
Copyright © 2011-2022 走看看