Ruby設計模式透析:適配器(Adapter)

來源:互聯網
上載者:User

今天一大早,你的leader就匆匆忙忙跑過來找到你:“快,快,緊急任務!最近ChinaJoy馬上就要 開始了,老闆要求提供一種直觀的方式,可以查看到我們新上線的遊戲中每個服的線上人數。”

你看了看日期,不是吧!這哪裡是馬上要開始了,分明是已經開始了!這怎麼可能來得及呢?

“沒關係的。”你的leader安慰你道:“功能其實很簡單的,介面都已經提供好了,你只需要 調用一下就行了。”

好吧,你勉為其難地接受了,對於這種突如其來的新需求,你早已習慣。

你的leader向你具體描述了一下需求,你們的遊戲目前有三個服,一服已經開放一段時間了, 二服和三服都是新開的服。設計的介面非常輕便,你只需要調用Utility.online_player_count (Fixnum),傳入每個服對應的數值就可以擷取到相應服線上玩家的數量了,如一服傳入1,二服傳入2, 三服則傳入3。如果你傳入了一個不存在的服,則會返回-1。然後你只要將得到的資料拼裝成XML就好, 具體的顯示功能由你的leader來完成。

好吧,聽起來功能並不是很複雜,如果現在就開始動工 好像還來得及,於是你馬上敲起了代碼。

首先定義一個用於統計線上人數的父類PlayerCount, 代碼如下:

class PlayerCount            def server_name          raise "You should override this method in subclass."    end              def player_count          raise "You should override this method in subclass."    end      end

接著定義三個統計類繼承PlayerCount,分別對應了三個不同的服,如下所示:

class ServerOne < PlayerCount            def server_name          "一服"    end              def player_count          Utility.online_player_count(1)      end      end
class ServerTwo < PlayerCount            def server_name          "二服"    end              def player_count          Utility.online_player_count(2)      end      end
class ServerThree < PlayerCount            def server_name          "三服"    end              def player_count          Utility.online_player_count(3)      end      end

然後定義一個XMLBuilder類,用於將各服的資料封裝成XML格式,代碼如下:

class XMLBuilder            def self.build_xml player          builder = ""        builder << "<root>"        builder << "<server>" << player.server_name << "</server>"        builder << "<player_count>" << player.player_count.to_s << "</player_count>"        builder << "</root>"    end      end

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.