看百度提供的雲推送服務端sdk代碼有感面向對象和麪向過程編碼思惟的區別

最近作一個小項目把消息主動推送到手機客戶端,因而研究了一下百度雲推送的api,由於我主要是作服務端這塊,因此重點就看了REST API這塊的文檔:http://developer.baidu.com/wiki/index.php?title=docs/cplat/push/api。 php

協議相對來講比較好理解,接下來就是按協議來寫代碼了,由於這個協議是基於http協議,因此首先想到的是用apache http client包來實現協議的請求,在我腦子裏第一時間蹦出來的代碼大概是這樣的:java

HttpClient httpClient = new DefaultHttpClient();
//根據實際狀況設置httpClient 的各類參數
....
//建立HttpPost實例,設置api的連接
HttpPost httpPost = new HttpPost("http://channel.api.duapp.com/rest/2.0/channel/channel");
//根據協議規定的格式拼裝參數值
String apiKey = ...
String secretKey = ...
String method = "push_msg";
String sign = .....
....
//構造post請求的參數
List <NameValuePair> nvps = new ArrayList <NameValuePair>(length); 
nvps.add(new BasicNameValuePair("method「, method);
nvps.add(new BasicNameValuePair("apiKey「, apiKey);
....
httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
//發送post請求
HttpResponse response = httpClient.execute(httpPost);
//獲取返回的數據解析處理等
......

嗯,僞代碼大概就是這樣了,而後我下載了百度提供的服務端sdk:http://bs.baidu.com/push-sdk-release/Baidu-Push-SDK-Java-1.1.2.zip,android

把文件解壓後,發現就是一個eclipse的工程,導入到eclipse後就能夠看到完整的代碼了,sdk除了提供sample例子代碼外,還提供了完整的協議封裝及發送請求的代碼(沒錯,百度沒有把這些封裝成jar,只提供jar包,仍是不錯的),參看sample中發送單播消息的代碼,以下:ios

package com.baidu.yun.channel.sample;

import com.baidu.yun.channel.auth.ChannelKeyPair;
import com.baidu.yun.channel.client.BaiduChannelClient;
import com.baidu.yun.channel.exception.ChannelClientException;
import com.baidu.yun.channel.exception.ChannelServerException;
import com.baidu.yun.channel.model.PushUnicastMessageRequest;
import com.baidu.yun.channel.model.PushUnicastMessageResponse;
import com.baidu.yun.core.log.YunLogEvent;
import com.baidu.yun.core.log.YunLogHandler;

public class AndroidPushMessageSample {

    public static void main(String[] args) {

        /*
         * @brief 推送單播消息(消息類型爲透傳,由開發方應用本身來解析消息內容) message_type = 0 (默認爲0)
         */

        // 1. 設置developer平臺的ApiKey/SecretKey
        String apiKey = "yBmx69aL5tAhiq7GlGFOsvV9";
        String secretKey = "6XtzFIMm17l61MrCAIaWZXc6db8PjfqD";
        ChannelKeyPair pair = new ChannelKeyPair(apiKey, secretKey);

        // 2. 建立BaiduChannelClient對象實例
        BaiduChannelClient channelClient = new BaiduChannelClient(pair);

        // 3. 若要了解交互細節,請註冊YunLogHandler類
        channelClient.setChannelLogHandler(new YunLogHandler() {
            @Override
            public void onHandle(YunLogEvent event) {
                System.out.println(event.getMessage());
            }
        });

        try {

            // 4. 建立請求類對象
            // 手機端的ChannelId, 手機端的UserId, 先用1111111111111代替,用戶需替換爲本身的
            PushUnicastMessageRequest request = new PushUnicastMessageRequest();
            request.setDeviceType(3); // device_type => 1: web 2: pc 3:android
                                      // 4:ios 5:wp
            request.setChannelId(3544710896330446635L);
            request.setUserId("908429798119406941");
            
            request.setMessage("Hello Channel");

            // 5. 調用pushMessage接口
            PushUnicastMessageResponse response = channelClient
                    .pushUnicastMessage(request);

            // 6. 認證推送成功
            System.out.println("push amount : " + response.getSuccessAmount());

        } catch (ChannelClientException e) {
            // 處理客戶端錯誤異常
            e.printStackTrace();
        } catch (ChannelServerException e) {
            // 處理服務端錯誤異常
            System.out.println(String.format(
                    "request_id: %d, error_code: %d, error_message: %s",
                    e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
        }

    }

}

跟我寫的代碼的結構有很大不一樣有木有?思惟不同有木沒有,呵呵,沒錯了,這就是面向對象的思惟了,主要邏揖都封裝在這三個類裏面了:web

BaiduChannelClientapache

PushUnicastMessageRequestapi

PushUnicastMessageResponseapp

其中BaiduChannelClient負責發送請求,PushUnicastMessageRequest負責請求協議的數據的封裝,PushUnicastMessageResponse負責返回數據的協議封裝。eclipse

其它不都說了,有興趣的同窗能夠仔細看一下百度sdk提供的代碼,大概就是這樣,整體感受仍是面向面向過程的思惟比較直接,但代碼不容易維護是事實,面向對象的思惟比較抽象,但代碼確實是整潔,容易維護,也容易作單元測試。ide

相關文章
相關標籤/搜索