隐藏或使私有类在内部运作的想法是更受偏爱的。尤其是由于缺省的CoffeeScript将编译的代码封装在自己的IIFE(闭包)中,你可以定义类而无须担心会被文件外部访问到。在这个实例中,注意,用惯用的模块导出特点来强调模块中可被公共访问的部分。(请看“导出到全局命名空间”中对此理解更深入的讨论)。
root = exports ? this
# Create a private class that we can initialize however
# defined inside the wrapper scope.
class ProtectedClass
constructor: (@message) ->
echo: -> @message
class Singleton
# You can add statements inside the class definition
# which helps establish private scope (due to closures)
# instance is defined as null to force correct scope
instance = null
# This is a static method used to either retrieve the
# instance or create a new one.
@get: (message) ->
instance ?= new ProtectedClass(message)
# Export Singleton as a module
root.Singleton = Singleton
我们可以注意到coffeescript是如此简单地实现这个设计模式。为了更好地参考和讨论JavaScript的实现,请看初学者必备 JavaScript 设计模式。
标签:CoffeeScript
相关阅读 >>
更多相关阅读请进入《CoffeeScript》频道 >>

Vue.js 设计与实现 基于Vue.js 3 深入解析Vue.js 设计细节
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者