W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
你需要準(zhǔn)備一個復(fù)雜的、多部分的對象,你希望操作不止一次或有不同的配置。
創(chuàng)建一個生成器封裝對象的產(chǎn)生過程。
Todo.txt格式提供了一個先進(jìn)的但還是純文本的方法來維護(hù)待辦事項列表。手工輸入每個項目有損耗且容易出錯,然而TodoTxtBuilder類可以解決我們的麻煩:
class TodoTxtBuilder
constructor: (defaultParameters={ }) ->
@date = new Date(defaultParameters.date) or new Date
@contexts = defaultParameters.contexts or [ ]
@projects = defaultParameters.projects or [ ]
@priority = defaultParameters.priority or undefined
newTodo: (description, parameters={ }) ->
date = (parameters.date and new Date(parameters.date)) or @date
contexts = @contexts.concat(parameters.contexts or [ ])
projects = @projects.concat(parameters.projects or [ ])
priorityLevel = parameters.priority or @priority
createdAt = [date.getFullYear(), date.getMonth()+1, date.getDate()].join("-")
contextNames = ("@#{context}" for context in contexts when context).join(" ")
projectNames = ("+#{project}" for project in projects when project).join(" ")
priority = if priorityLevel then "(#{priorityLevel})" else ""
todoParts = [priority, createdAt, description, contextNames, projectNames]
(part for part in todoParts when part.length > 0).join " "
builder = new TodoTxtBuilder(date: "10/13/2011")
builder.newTodo "Wash laundry"
# => '2011-10-13 Wash laundry'
workBuilder = new TodoTxtBuilder(date: "10/13/2011", contexts: ["work"])
workBuilder.newTodo "Show the new design pattern to Lucy", contexts: ["desk", "xpSession"]
# => '2011-10-13 Show the new design pattern to Lucy @work @desk @xpSession'
workBuilder.newTodo "Remind Sean about the failing unit tests", contexts: ["meeting"], projects: ["compilerRefactor"], priority: 'A'
# => '(A) 2011-10-13 Remind Sean about the failing unit tests @work @meeting +compilerRefactor'
TodoTxtBuilder類負(fù)責(zé)所有文本的生成,讓程序員關(guān)注每個工作項的獨特元素。此外,命令行工具或GUI可以插入這個代碼且之后仍然保持支持,提供輕松、更高版本的格式。
并不是每次創(chuàng)建一個新的實例所需的對象都要從頭開始,我們將負(fù)擔(dān)轉(zhuǎn)移到一個單獨的對象,可以在對象創(chuàng)建過程中進(jìn)行調(diào)整。
builder = new TodoTxtBuilder(date: "10/13/2011")
builder.newTodo "Order new netbook"
# => '2011-10-13 Order new netbook'
builder.projects.push "summerVacation"
builder.newTodo "Buy suntan lotion"
# => '2011-10-13 Buy suntan lotion +summerVacation'
builder.contexts.push "phone"
builder.newTodo "Order tickets"
# => '2011-10-13 Order tickets @phone +summerVacation'
delete builder.contexts[0]
builder.newTodo "Fill gas tank"
# => '2011-10-13 Fill gas tank +summerVacation'
擴(kuò)大project-和context-tag生成代碼來過濾掉重復(fù)的條目。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: