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 設計模式
156
   
第七章
而你的商店在美國,於是買家除了必須支付美國聯邦稅之外,還得支付魁北克省的稅。遵
decorator 模式的做法,你會用聯邦稅的 decorator 和魁北克稅的 decorator 來「裝飾」
sale
物件。你也可以接著將格式化售價的功能附加至物件上。就像下面這個樣子:
如果有另一個情況,如果買家位在不需要課稅的省份,並且你想要將金額格式化成加拿大
元,你可以這麼做:
如你所見,這是一種不論是在執行時期增加功能或者調整物件都很有彈性的方式。讓我們
來看看如何實作此模式。
實作
實作 decorator 模式的一種方式,是將每個 decorator 實作為一個物件,其包含一些必須要
覆寫的方法。每個 decorator 將會繼承當前的上一份物件。每個「裝飾用」的方法都呼叫來
uber
(繼承的上個物件)的同名方法,取得結果之後,繼續屬於這個方法的工作。[151]
結果是當你呼叫第一個使用範例的
sale.getPrice()
,你其實是在呼叫
money
decorator
方法(見圖 7-1)。但因為每個裝飾方法都會先呼叫父物件,於是
money
getPrice()
呼叫
quebec
getPrice()
,而它又呼叫
fedtax
getPrice()
。循著這條連鎖關係一路
到最上層,會呼叫未經過任何裝飾、屬於
Sale()
建構式的
getPrice()
售價是 100
售價是 100
加上聯邦稅
加上聯邦稅
再加上魁北克省稅
格式化成加拿大元 ...
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