课程表

CoffeeScript 语法

CoffeeScript 类和对象

CoffeeScript 字符串

CoffeeScript 数组

CoffeeScript 日期和时间

CoffeeScript 数学

CoffeeScript 方法

CoffeeScript 元编程

CoffeeScript jQuery

CoffeeScript 正则表达式

CoffeeScript 网络

CoffeeScript 设计模式

CoffeeScript 数据库

CoffeeScript 测试

工具箱
速查手册

CoffeeScript 单件模式

当前位置:免费教程 » JS/JS库/框架 » CoffeeScript

问题

许多时候你想要一个,并且只要一个类的实例。比如,你可能需要一个创建服务器资源的类,并且你想要保证使用一个对象就可以控制这些资源。但是使用时要小心,因为单件模式可以很容易被滥用来模拟不必要的全局变量。

解决方案

公有类只包含获得一个实例的方法。实例被保存在该公共对象的闭包中,并且总是有返回值。

这很奏效因为 CoffeeScript 允许你在一个类的声明中定义可执行的状态。但是,因为大多数 CoffeeScript 编译成一个 IIFE 包,如果这个方式适合你,你就不需要在类的声明中放置私有的类。之后的内容可能对开发模块化代码有所帮助,例如 CommonJS(Node.js)或 Require.js 中可见(见实例讨论)。

  1. class Singleton
  2. # You can add statements inside the class definition
  3. # which helps establish private scope (due to closures)
  4. # instance is defined as null to force correct scope
  5. instance = null
  6. # Create a private class that we can initialize however
  7. # defined inside this scope to force the use of the
  8. # singleton class.
  9. class PrivateClass
  10. constructor: (@message) ->
  11. echo: -> @message
  12. # This is a static method used to either retrieve the
  13. # instance or create a new one.
  14. @get: (message) ->
  15. instance ?= new PrivateClass(message)
  16. a = Singleton.get "Hello A"
  17. a.echo() # => "Hello A"
  18. b = Singleton.get "Hello B"
  19. b.echo() # => "Hello A"
  20. Singleton.instance # => undefined
  21. a.instance # => undefined
  22. Singleton.PrivateClass # => undefined

讨论

通过上面的实例我们可以看到,所有的实例是如何从同一个 Singleton 类的实例中输出的。你也可以看到,私有类和实例变量都无法在 Singleton class 外被访问到。 Singleton class 的本质是提供一个静态方法得到只返回一个私有类的实例。它也对外界也隐藏私有类,因此你无法创建一个自己的私有类。

隐藏或使私有类在内部运作的想法是更受偏爱的。尤其是由于缺省的 CoffeeScript 将编译的代码封装在自己的 IIFE(闭包)中,你可以定义类而无须担心会被文件外部访问到。在这个实例中,注意,用惯用的模块导出特点来强调模块中可被公共访问的部分。(请看 “导出到全局命名空间” 中对此理解更深入的讨论)。

  1. root = exports ? this
  2. # Create a private class that we can initialize however
  3. # defined inside the wrapper scope.
  4. class ProtectedClass
  5. constructor: (@message) ->
  6. echo: -> @message
  7. class Singleton
  8. # You can add statements inside the class definition
  9. # which helps establish private scope (due to closures)
  10. # instance is defined as null to force correct scope
  11. instance = null
  12. # This is a static method used to either retrieve the
  13. # instance or create a new one.
  14. @get: (message) ->
  15. instance ?= new ProtectedClass(message)
  16. # Export Singleton as a module
  17. root.Singleton = Singleton

我们可以注意到 coffeescript 是如此简单地实现这个设计模式。为了更好地参考和讨论 JavaScript 的实现,请看初学者必备 JavaScript 设计模式

转载本站内容时,请务必注明来自W3xue,违者必究。
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号