使用类对象访问超级变量

时间:2014-06-30 10:48:34

标签: ruby oop inheritance factory-pattern class-variables

Heey我是Ruby的新手。我需要创建一个工厂方法,它将返回一个类的对象。使用该对象,我应该能够访问类的变量。我写了以下代码,但我肯定错过了一些东西。

class Super
  @@super_temp = 1

  def Super.get_instance(world)          
    platform = world
    if @@instance == nil
      if platform==1
        @@instance = BaseA.new
      else
        @@instance = BaseB.new
      end
    end
    return @@instance
  end
end

class BaseA < Super    
  @@base_temp = 2      
end


class BaseB < Super
  @@base_temp = 3    
end


class Demo
  def Demo.call_demo
    obj = Super.get_instance(0)

    puts "---------temp is #{obj.base_temp}"      
  end
end

Demo.call_demo

我需要在类Demo中检索base_temp的值。

1 个答案:

答案 0 :(得分:2)

请勿使用@@Why should we avoid using class variables @@ in rails?) - @轻松解决您的问题。

除此之外,代码中缺少的只是一个getter:

class Super
  @super_temp = 1

  def Super.get_instance(world)          
    platform = world
    if @instance == nil
      if platform==1
        @instance = BaseA.new
      else
        @instance = BaseB.new
      end
    end
    return @instance
  end

  def base_temp
    self.class.base_temp
  end

  def self.base_temp
    @base_temp
  end
end

class BaseA < Super    
  @base_temp = 2      
end


class BaseB < Super
  @base_temp = 3    
end


class Demo
  def Demo.call_demo
    obj = Super.get_instance(0)

    puts "---------temp is #{obj.base_temp}"      
  end
end

Demo.call_demo
# ---------temp is 3

实例getter(实现为self.class.base_temp)调用实例类的类方法base_temp。如果我们添加函数内部产品的打印件,您可以对其内部结构有一些见解:

class Super
  def base_temp
    p self
    p self.class
    p self.class.base_temp
  end
end

BaseA.new.base_temp
# #<BaseA:0x000000027df9e0>
# BaseA
# 2

BaseB.new.base_temp
# #<BaseB:0x000000027e38b0>
# BaseB
# 3