2012-06-20 38 views
2

這是我第一次參與爲外部服務器編寫完整的客戶端(我對設計模式非常新穎)。爲支持多協議的服務器設計客戶端

該服務器提供了多種協議來連接和發送命令,例如, REST,SOAP等等。

所有這些協議執行幾乎相同的一組操作,但它不同。我需要設計和實現一個完整的客戶端框架,它將支持所有這些協議。

由於理解和經歷了幾個互聯網鏈接,在我看來使用抽象工廠模式和接口。

我的implementating是如下當前思想:

  1. 用於連接創建一個抽象工廠類(連接工廠)。根據輸入,提及要使用的協議,將創建相應的Connection對象。這個抽象類將有一個抽象方法(processMessage)。該方法必須在所有協議的連接類中實現。這個單一方法(processMessage)將提供一個提及要執行的請求類型的arugument。每個協議都有一個單獨的請求名稱。我如何使用常量來照顧它?

  2. 定義請求,響應和客戶端的接口。所有的協議都有自己的Request,Response和Client類,它們將實現它們各自的接口。

請提供給我關於此設計的寶貴意見;請給我更好的建議,我可以在這裏做。 我仍然無法完成目錄結構,請幫助我一樣。

回答

2

如果您計劃爲不同協議定義類層次結構,請儘量避免爲數據類型(請求,響應等)創建並行層次結構。這通常被認爲是反模式,被稱爲「並行繼承層次結構」。這裏是一個例子question。這種方法的主要缺點是必須維護多個並行類層次結構。

創建連接工廠聽起來很合理。它應該最有可能將消息發送服務器和而processMessage()用於接收消息服務器和工廠將插件ProtocolHandler解釋下一個返回具有方法的CreateMessage一個類的實例()。

至於請求和響應,您可以使用Strategy pattern在Connection類中定義一個ProtocolHandler成員,其中每個實現都可以處理,解析,編組等等各個協議的詳細信息(REST,SOAP等)。 Connection類processMessage()和createMessage()方法將使用ProtocolHandler類層次結構。

這裏是一些在C++中的僞代碼,我沒有編譯也沒有測試過它,但我希望它能給你一個關於我試圖解釋什麼的好主意。

// Your factory will create the Connection instance and fill in the 
// corresponding ProtocolHandler concrete implementation instance 

class Connection 
{ 
public: 
    // Depending on what else you need for the Connection, 
    // the constructors may be different 
    Connection() : handler_(NULL) {} 
    Connection(ProtocolHandler *handler) : handler_(handler) {} 

    inline void setProtocolHandler(ProtocolHandler *handler) {handler_ = handler;} 
    inline ProtocolHandler *getProtocolHandler() {return handler_;} 

    void processMessage(const string &msg) { 
     handler_->decode(msg); 
     // any extra logic here 
    } 

    string createMessage() { 
     // any extra logic here 
     return handler_->encode(); 
    } 

    // Put the rest of your connection stuff here 

private: 
    ProtocolHandler *handler_; 

}; 

// Notice that Im handling the protocol msg buffers in a std::string, this 
// may or may not work for you, replace accordingly depending on your needs 

class ProtocolHandler 
{ 
public: 

    // abstract methods 
    // name these accordingly as handle, parse, marshal, etc 
    virtual string encode() = 0; 
    virtual void decode(const string &msg) = 0; 

    // Other methods you may need here 
}; 

class RestProtocolHandler : public ProtocolHandler 
{ 
public: 
    virtual string encode() { /* your rest msg encode impl here */ } 
    virtual void decode(const string &msg) { /* your rest msg decode impl here */ } 

    // Other methods and/or attributes you may need here 
}; 

// More concrete ProtocolHandler implementations here 
+0

很好的回覆!感謝您的及時答覆。 – rpg

+0

@rpg,謝謝,很高興幫助。 – Brady

+0

請提出一個問題。在你的第一段中,你提到了不具有不同協議的類層次結構。在這種情況下,我如何爲每個協議分別設置一個請求和響應類。如果可能的話,我會請你請分享一些僞代碼。 – rpg

相關問題