我有一个类想要加工厂方法,根据两种构造方法之一生成新实例:一是基于内存中的数据构造,另一种是基于文件中存储的数据构造。
我希望将构建逻辑封装在类内部,因此我希望设置静态类方法如下:
我希望将构建逻辑封装在类内部,因此我希望设置静态类方法如下:
class MyAppModel
def initialize
#Absolutely nothing here - instances are not constructed externally with MyAppModel.new
end
def self.construct_from_some_other_object otherObject
inst = MyAppModel.new
inst.instance_variable_set("@some_non_published_var", otherObject.foo)
return inst
end
def self.construct_from_file file
inst = MyAppModel.new
inst.instance_variable_set("@some_non_published_var", get_it_from_file(file))
return inst
end
end
是否有一种不需要使用元编程(instance_variable_set)就可以从类本身设置实例上的@some_private_var的方法?这种模式似乎并不像需要将变量元编程到实例中那样奇怪。我真的不想让MyAppModel以外的任何类都能访问some_published_var,所以我不想使用例如attr_accessor - 感觉好像我错过了什么...