【翻译】Ruby: Lazily Initialized Attributes
url(注:原文网址访问不到,估计是被和谐了):
http://blog.jayfields.com/2007/07/ruby-lazily-initialized-attributes.html
http://95555.info/index.php?q=aHR0cDovL2Jsb2cuamF5ZmllbGRzLmNvbS8yMDA3LzA3L3J1YnktbGF6aWx5LWluaXRpYWxpemVkLWF0dHJpYnV0ZXMuaHRtbA%3D%3D&hl=0111101001&s=mza5mdcxmjewndjon01vbjbwbq==
在第一次访问一个attribute时对其进行初始化,而不是在构造函数里面完成。
[code]
class Employee
def initialize
@emails = []
end
end
[/code]
变为
[code]
class Employee
def emails
unless instance_variable_defined?(:@emails)
@emails = []
end
@emails
end
end
[/code]
动机:
增加代码可读性。
上述例子非常简单。如果Employee这个类有多个属性需要初始化的话,构造函数就需要包含所有的初始化逻辑。而采取lazy initialization的方式可以把各个属性的初始化逻辑放置在它们自己的访问函数中。
运作机制:
将初始化逻辑移到属性的getter方法中
示例见上。
分享到:
相关推荐
Ruby对象属性实验室 目标 定义Ruby类。 定义读取和写入实例变量的方法。 使用方法和实例变量创建对象属性。 概述 本实验全部关于使用类中的实例变量来创建表示对象的属性或属性的方法。 指示 通过打开“ learn ...
一种更友好、无依赖的 ruby 对象初始化方法。 用法 宝石档案: gem 'better-initialize', github: 'huned/better-initialize' 代码: require 'better_initialize' class Pizza include BetterInitialize ...
要将查到的Graphic(不同图层字段的多少可能不一样)的属性在DataGrid中显示(字段为一列,属性值为一列)。由于Graphic的属性attributes为Object类型,不能直接与DataGrid绑定或在DataGrid中达不到预期效果。本文...
CSharp - Module 14_Attributes
具有特定名称的列会导致错误,因为它们会导致ActiveRecord以不兼容的方式在Ruby或ActiveRecord中重新定义键方法。 一个经典的示例是任何带有名为“ class”的列的表,尽管还有其他可能的示例。 简而言之,使用该gem...
commons-attributes-2.2.zipcommons-attributes-2.2.zipcommons-attributes-2.2.zipcommons-attributes-2.2.zipcommons-attributes-2.2.zipcommons-attributes-2.2.zip
Laravel开发-attributes Rinvex属性是一种健壮、智能和集成的实体属性值模型(EAV)实现,用于Laravel雄辩,具有强大的底层功能,可以轻松地将实体属性隐式管理为关系。它利用了Laravel雄辩的力量,平滑无缝的集成。
RADIUS Attributes
Attributes结构的一个总结,适合java开发者使用。
一个对XmlDocument的DocumentElement 以及其属性Attributes进行访问的类库函数。
org-gephi-data-attributes-api可视化软件gephi的插件,nbm格式,
JavaEE源代码 commons-attributes-apiJavaEE源代码 commons-attributes-apiJavaEE源代码 commons-attributes-apiJavaEE源代码 commons-attributes-apiJavaEE源代码 commons-attributes-apiJavaEE源代码 commons-...
介绍了Adaptive Color Attributes for Real-Time Visual Tracking,CVPR2014,文章中算法的基本流程,以及优化的重点
commons-attributes-compiler-2.2.zipcommons-attributes-compiler-2.2.zipcommons-attributes-compiler-2.2.zipcommons-attributes-compiler-2.2.zipcommons-attributes-compiler-2.2.zip
commons-attributes-api.jar,commons-attributes-compiler.jar,commons-beanutils.jar,commons-codec.jar,commons-collections.jar,commons-dbcp.jar,commons-digester.jar,commons-discovery.jar,commons-...
tkinter的menu attributes示例代码,结合https://blog.csdn.net/weixin_43708622/article/details/107053182一起学习
commons-attributes-api.jar
commons-attributes-api-2.2.jar。学习资源,