2011-02-09 67 views
7

我有一个类,我希望将工厂方法放在基于两种构造方法之一的基础上吐出一个新的实例:它可以从内存中的数据构建,或存储在文件中的数据。Ruby中的类静态实例初始值设定项(即工厂方法)

我想什么做的是封装的结构是如何在类中执行的逻辑,所以我想有一个正在建立这样的静态类方法:

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 

有没有办法从类本身的类实例上设置@some_private_var而不诉诸元编程(instance_variable_set)?看起来这种模式并不是那么深奥,以至于不需要将meta-poking变量变为实例。我真的不打算让MyAppModel以外的任何类访问some_published_var,所以我不想使用例如attr_accessor - 它只是觉得我失去了一些东西...

回答

9

也许使用构造函数是实现你想要的更好的方法,只是让它保护,如果你不想从“外部”

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 2011-02-09 23:57:47

相关问题