2012-02-13 21 views
5

鑑於一些庫實現了一些廣泛的協議或類似的東西(比如FTP),我將如何保持我的標準兼容代碼與只需要代碼的代碼分離與不那麼標準的兼容系統合作?如何從傳統/怪癖模式代碼中分離出良好的代碼

一個很好的例子,這也是有意義的恕我直言,像jQuery這樣的圖書館必須考慮所有這些瀏覽器的特性。必須保持傳統兼容性的項目可能也會成爲此類技術的良好目標受衆。

我對ruby解決方案特別感興趣,但也歡迎語言獨立模式或來自其他語言的良好示例。

我已經在stackoverflow上找到了related question這裏,但還有其他的方法嗎?

回答

3
  1. 爲不同的模式定義不同的實現(這可以防止您必須將「良好」代碼與恰好存在的代碼混合以保持向後兼容性)。理想情況下,遺留層僅僅是符合標準的代碼的一個包裝。
  2. 檢測底層系統(瀏覽器,遠程服務器...)是否符合標準。這是如何詳細完成的,顯然高度依賴於具體情況。
  3. 爲特定系統選擇正確的實施方式並將其透明地插入。
  4. 給用戶一個機會來檢查我們是哪種模式並強制特定模式。

紅寶石小例子:

class GoodServer 
    def calculate(expr) 
    return eval(expr).to_s 
    end 
end 

class QuirkyServer 
    def calculate(expr) 
    # quirky server prefixes the result with "result: " 
    return "result: %s" % eval(expr) 
    end 
end 

module GoodClient 
    def calculate(expr) 
    @server.calculate(expr) 
    end 
end 

# compatibility layer 
module QuirkyClient 
    include GoodClient 
    def calculate(expr) 
    super(expr).gsub(/^result: /, '') 
    end 
end 

class Client 
    def initialize(server) 
    @server = server 
    # figure out if the server is quirky and mix in the matching module 
    if @server.calculate("1").include?("result") 
     extend QuirkyClient 
    else 
     extend GoodClient 
    end 
    end 
end 

good_server = GoodServer.new 
bad_server = QuirkyServer.new 

# we can access both servers using the same interface 
client1 = Client.new(good_server) 
client2 = Client.new(bad_server) 

p client1.is_a? QuirkyClient # => false 
p client1.calculate("1 + 2") # => "3" 

p client2.is_a? QuirkyClient # => true 
p client2.calculate("1 + 2") # => "3" 
+0

同樣,一個非常精細和全面的答覆。非常感謝。 – raphinesse 2012-02-14 18:30:56