gpt4 book ai didi

ruby - Ruby 中的类静态实例初始值设定项(即工厂方法)

转载 作者:数据小太阳 更新时间:2023-10-29 06:58:57 24 4
gpt4 key购买 nike

我有一个类,我想在该类上放置工厂方法,以基于两种构造方法之一吐出一个新实例:它可以从内存中的数据构造,也可以从文件中存储的数据构造。

我想做的是将构建的逻辑封装在类内部,所以我想有这样设置的静态类方法:

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 - 感觉好像遗漏了什么......

最佳答案

也许使用构造函数是实现你想要的更好的方法,如果你不想从“外部”创建实例,只需将其保护起来

class MyAppModel
class << self
# ensure that your constructor can't be called from the outside
protected :new

def construct_from_some_other_object(other_object)
new(other_object.foo)
end

def construct_from_file(file)
new(get_it_from_file(file))
end
end

def initialize(my_var)
@my_var = my_var
end
end

关于ruby - Ruby 中的类静态实例初始值设定项(即工厂方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4950454/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com