Skip to Content
JavaScript 設計模式
book

JavaScript 設計模式

by Stoyan Stefanov
March 2012
Intermediate to advanced
244 pages
4h 42m
Chinese
GoTop Information, Inc.
Content preview from JavaScript 設計模式
174
   
第七章
7-7 Mediator 模式中的參與者
Mediator 範例
我們來研究一個使用 mediator 模式的例子。這是一個遊戲,有兩個玩家,他們都有半分
鐘來狂按按鈕,按得較多下的人贏。玩家一按的是數字 1,而玩家二按的是數字 0(這樣
他們可以感覺比較舒服點,而不會為了搶鍵盤去打架)。還有個計分板會不斷更新目前的
分數。
參與的物件包括有:

玩家一

玩家二

計分板

Mediator [168]
這裡的 mediator 知道其他所有物件。它和輸入裝置(鍵盤)溝通、處理按鍵事件、判斷哪
個玩家有所行動,並通知變動(請見圖 7-8)。當玩家有玩的動作(意思是增加自己的分
數一分)會通知 mediator,此時 mediator 會將新的分數通知給計分板,計分板接著就會刷
新顯示。
除了 mediator 之外,沒有任何物件知道其他物件發生了什麼事。這讓更新這款遊戲變得輕
鬆寫意。例如,新增一個玩
家或者額外再顯示剩餘時間。
設計模式
   
175
你可以在 http://jspatterns.com/book/7/mediator.html 看到此遊戲的線上版本,也可以閱讀其
原始碼。
7-8 按鍵遊戲中的參與者
玩家物件由
Player()
建構式所建立,它具有屬性
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

JavaScript 之美

JavaScript 之美

Anton Kovalyov
重構 JavaScript

重構 JavaScript

Evan Burchard

Publisher Resources

ISBN: 9789862764190