適配器模式(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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章