Adapter

…衆ロ難τιáo~ 提交于 2020-03-20 07:02:04

今天是第一次在Mac book上编程,与在windows上写代码相比,既新鲜又充斥在许多小问题,还好很快掌握了

Adapter:

适配器Adapter是一种结构设计模式,其主要作用是允许不兼容的对象间通过一个转换接口协同工作。

适配器本身扮演的角色是两个对象间的包装器,通过对不兼容的对象进行包装从而生成目标对象的统一接口。

其实现就是适配器从目标对象继承,然后聚合不兼容的对象

#include <iostream>
#include <string>

class Target
{
public:
    virtual ~Target() = default; 
    virtual std::string Request() const 
    {
        return "Target: The default target's behavior.";
    }
};

class Adaptee
{
public:
    std::string SpecificRequest() const{
        return ".eetpadA eht fo rovivaheb laicepS";
    }
};

class Adapter : public Target
{
private:
    Adaptee *m_pAdaptee;

public:
    Adapter(Adaptee* pAdaptee):m_pAdaptee(pAdaptee){

    }
    virtual std::string Request() const override{
        std::string to_reverse = this->m_pAdaptee->SpecificRequest();
        std::reverse(to_reverse.begin(), to_reverse.end());
        return "Adapter:(TRANSLATED) " + to_reverse;
    }
};

void ClientCode(const Target* pTarget){
    std::cout << pTarget->Request();
}

int main()
{
    std::cout << "Client: I can work just like fine with the Target objects:\n";

    Target* pTarget =new Target;
    ClientCode(pTarget);
    std::cout << "\n" << std::endl;

   Adaptee* pAdaptee = new Adaptee;
   std::cout << "Client: The Adaptee class has a weird interface. See, I don't understand\n";
   std::cout << "Adapte: " << pAdaptee->SpecificRequest();
   std::cout << "\n\n";
   std::cout << "Client: But I can work with it via the Adapter:\n";
   
   Adapter* pAdapter = new Adapter(pAdaptee);
   ClientCode(pAdapter);
   std::cout << "\n";

   delete pTarget;
   pTarget = NULL;
   delete pAdaptee;
   pAdaptee = NULL;
   delete pAdapter;
   pAdapter = NULL;

   return 0;
}

 mac book上编译:

g++ -std=c++11 -o adapter adapter.cpp

 

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!