MyClass对象具有a、b和c实例变量(请原谅我的模糊抽象)。此外,在编写这些类时,我希望能够设置a、b和c,但我不希望我的用户能够这样做。
class MyClass
attr_accessor :a, :b, :c
private :a=, :b=, :c=
end我希望通过以下两种方式之一实例化MyClass:
f = MyClass.create_from_foo foo_data
b = MyClass.create_from_bar bar_data并在f和b中获取b的实例。f和b在实例化后是不可区分的,但当然是以不同的方式创建的。在这些调用之后,f和b都有一个a、b和c。
我不希望MyClass通过new实例化。由于这两种创建方法都同样有效,我觉得“更喜欢”foo_data而不是bar_data,反之亦然。因此,我觉得我应该将new私有化,并且只允许这些类方法创建MyClass实例,以尝试公平竞争环境。换句话说,我试图避免:
#don't want this
f = MyClass.new foo_data
b = MyClass.create_from_bar bar_data #not quite "fair" to bar_data那么,让我开始编写这些create_from_<type>类方法:
class MyClass
#from earlier
attr_accessor :a, :b, :c
private :a=, :b=, :c=
private_class_method :new
def MyClass.create_from_foo foo_data
#some parsing of foo_data and computation of a, b, and c
myclass = MyClass.new
myclass.a = a
myclass.b = b
#...
end
def MyClass.create_from_bar bar_data
#again, computation of bar_data
myclass.a = a
myclass.b = b
#...
end
end现在,如果你一直跟着,你会注意到我不能这样做!我把自己堵住了!
new进行了私有化,因为我不希望我的用户以这种方式制作MyClass对象。我希望他们使用类方法。在类方法定义空间中,我基本上是一个用户,a=、b=和c=,因为我不希望我的用户改变这些东西。(这将打破我的现实世界的例子)。然而,在定义类方法时,我还是一个用户。所以,这就是我的工作。如何在类方法中创建“限制性”类的实例?
发布于 2012-02-13 01:50:15
你有点纠结,你可以做得更简单一点。
class MyClass
attr_reader :a, :b, :c
private_class_method :new
def initialize(a,b)
@a = a
@b = b
end
def self.create_from_foo foo_data
#some parsing of foo_data and computation of a, b, and c
myclass = new(a,b)
#...
end
def self.create_from_bar bar_data
#again, computation of bar_data
myclass = new(a,b)
#...
end
end发布于 2012-02-13 01:29:02
完全可以从其他类方法调用私有类方法。但是,在Ruby中,不能使用显式接收器调用私有方法(setters除外)。
因此,如果您只编写new而不是MyClass.new,它就会工作得很好。
https://stackoverflow.com/questions/9254506
复制相似问题