Ruby中的类静态实例初始化器(即工厂方法)

8
我有一个类想要加工厂方法,根据两种构造方法之一生成新实例:一是基于内存中的数据构造,另一种是基于文件中存储的数据构造。
我希望将构建逻辑封装在类内部,因此我希望设置静态类方法如下:
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 - 感觉好像我错过了什么...

1个回答

11

也许使用构造函数是实现你想要的功能的更好方式,如果你不想从"外部"创建实例,只需将其设置为受保护的

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

1
这非常好,而且很符合惯用语。 - Chuck
谢谢,我认为这比我之前的做法更加干净 - 它仍然涉及将一堆东西传递给构造函数,但由于它已经是受保护的了,所以没有大问题 - 比使用instance_variable_set好多了。 - Matt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接