CoffeeScript 生成器模式

2022-06-29 17:14 更新

生成器模式

問題

你需要準(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可以插入這個代碼且之后仍然保持支持,提供輕松、更高版本的格式。

前期建設(shè)

并不是每次創(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'

練習(xí)

  • 擴(kuò)大project-和context-tag生成代碼來過濾掉重復(fù)的條目。

  • 一些Todo.txt用戶喜歡在任務(wù)描述中插入項目和上下文的標(biāo)簽。添加代碼來識別這些標(biāo)簽和過濾器的結(jié)束標(biāo)記。
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號