适配器模式(C++实现)之戏说手机数据线

适配器模式(adapter_pattern)

好久没更新设计模式的博客了,懒得去死呀-_-
想看适配器模式的详细介绍还是推荐菜鸟教程呀——菜鸟教程|适配器模式
我这里只谈谈自己的学习体会,一开始感觉适配器模式和工厂模式有点像。工厂模式对外暴露出一个工厂类,你想要什么只要告诉这个工厂类就可以了,它会给你安排一个你想要的对象;有点像的是适配器模式对外也暴露一个适配器类,你想要干什么告诉适配器类就可以了,它会去联系具体的类来满足你的需求。但是仔细想下,类的结构上还是蛮大差别的,具体就一起来看下UML图吧

UML图

工厂模式

在这里插入图片描述
ShapeFactory是一个形状工厂,你想要圆形、正方形还是长方形告诉ShapeFactory就完事了。

适配器模式

在这里插入图片描述
three_in_one_data_line是一个适配器,不管你的手机是哪种接口,用它就完事了。
这样一对比就很明显嘛,适配器是多继承的一个类,它拥有各个父类的功能;而工厂是一个拥有各种对象的类,它会给你想要的对象。

代码实现

data_line.h

#ifndef _DATA_LINE_
#define _DATA_LINE_

#include <iostream>
#include <string>

using namespace std;

class type_c_data_line
{
public:
    void charge(string line_type)
    {
        if (line_type == "type_c")
            cout << line_type << "match successful,start charging." << endl;
        else
            cout << line_type << "match failed,can't charge." << endl;
    }
};

class android_data_line
{
public:
    void charge(string line_type)
    {
        if (line_type == "android")
            cout << line_type << "match successful,start charging." << endl;
        else
            cout << line_type << "match failed,can't charge." << endl;
    }
};

class ios_data_line
{
public:
    void charge(string line_type)
    {
        if (line_type == "ios")
            cout << line_type << "match successful,start charging." << endl;
        else
            cout << line_type << "match failed,can't charge." << endl;
    }
};

class three_in_one_data_line:public ios_data_line,public android_data_line,public type_c_data_line
{
public:
    void charge(string line_type)
    {
        if (line_type == "ios")
            ios_data_line::charge(line_type);
        else if (line_type == "android")
            android_data_line::charge(line_type);
        else if (line_type == "type_c")
            type_c_data_line::charge(line_type);
        else
            cout << line_type << "match failed,can't charge." << endl;
    }
};
#endif
adapter_pattern.cpp

#include <iostream>
#include <string>
#include "data_line.h"
using namespace std;

int main(int argc, char const *argv[])
{
    string nova2s = "type_c";
    type_c_data_line type_c_line;
    android_data_line android_line;
    ios_data_line ios_line;
    three_in_one_data_line three_in_one_line;
    type_c_line.charge(nova2s);
    android_line.charge(nova2s);
    ios_line.charge(nova2s);
    three_in_one_line.charge(nova2s);
    return 0;
}


结果

![在这里插入图片描述](https://img-blog.csdn.net/20181007234939519?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0xvbmVseUdhbWJsZXI=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70

猜你喜欢

转载自blog.csdn.net/LonelyGambler/article/details/82962794