Ruby元编程技术详解Ruby Metaprogramming techniques ... 1. 使用单例类Use the singleton-class 当你想创建一个DSL来定义类信息时,最常见的问题是怎样表示信息来让框架的其它部分使用。以定义一个ActiveRecord模型对象为例: Q 这里令人感兴趣的是define_attr_method。在这个例子中我们需要获得Product类的单例类,但又不想修改ActiveRecord::Base。通过使用单例类我们达到了这个目的。我们为原来的方法取别名,再定义新的存取器(accessor)来返回值。如果ActiveRecord需要table 敶 name就可以直接调用存取器。这种动态创建方法和存取器的技术在单例类是很常见的,特别是Rails。 ...
基于8个网页-相关网页
This has the added benefit of separating singleton code from the class code leaving the flexibility to use several instances of the class or using the class as a singleton.
这样分离出单例结构的代码,将有利于保持按单例模式使用类或不按单例模式使用类的灵活性。
Those who use it will find that they often have to write the same code each time they want to create a different Singleton class.
他们会发现每次他们要创建一个不同的单例类的时候,都不得不写同样得代码。
应用推荐