Adapter

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

Adapter:

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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#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

 

 

posted @   unicornsir  阅读(779)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示