如何在方法中使用其他子类

时间:2014-11-02 02:50:51

标签: ruby inheritance

我正在使用Gadget类,其中包含initialize方法(品牌,型号,价格,重量,高度,宽度)。 Gadget有三个子类:IPhone5sIPhone6sIPhone6。我需要有关继承方法createiPhone的帮助。

我正在努力在方法createiPhone中打印其他子类。我想在用户创建iPhone6s时使用iPhone6PlusiPhone6s,然后将价格输出到方法createiPhone中。关于如何处理这个问题的任何建议都是有用的。

AppleStore的功能:

def createiPhone (model)

    a = Gadget.new(:iPhone, model, 99.00, 4.87, 2.31, 3.95);

    @@reveune_earned += money_made(a.price) 
    @@no_of_products +=1 
     puts " A  #{model} that cost $ #{a.price}0 weighing #{a.weight} ounces  "
    puts " A store having sold #{ @@no_of_products} with revenue earned #{@@reveune_earned}"
    return a 
end 

派生类:

class IPhone5s < Gadget
     def initialize( make)
        super( :iPhone, "5s".to_sym, 99.00, 4.87, 2.31, 3.95) #make, model, price, weight, height, width 
#, 99.00, 4.87, 2.31, 3.95, 
    end 
end 

class IPhone6s < Gadget
    def initialize( model)
        super( :iPhone, "6s".to_sym, 199.00, 4.55, 5.44, 2.64) 

    end 

end 

class IPhone6Plus < Gadget
    def initialize( model)
        super( :iPhone, "6s".to_sym, 299.00, 6.07, 6.22, 3.06) 

    end 
end 

测试仪:

puts "here is your iphone5s"
p = AppleStore.new()
iphone5 = p.createiPhone(:iPhone5s)
puts "here at the AppleStore" 

输出:

here is your iphone6
  A  iPhone5s that cost $ 99.00 weighing 4.87 ounces
 A store having sold 3 with revenue earned 1348.0
here at the AppleStore

1 个答案:

答案 0 :(得分:0)

我认为您可以使用Abstract Factory Pattern来实现这一目标。例如,这里的代码可能适用于您的情况:

class AppleStore

  @@reveune_earned = 0
  @@no_of_products = 2

  def createiPhone(model)
    a = Gadget.create(:iPhone, model, 99.00, 4.87, 2.31, 3.95);
    @@reveune_earned += money_made(a.price) 
    @@no_of_products +=1 
    puts " A  #{model} that cost $ #{a.price}0 weighing #{a.weight} ounces  "
    puts " A store having sold #{ @@no_of_products} with revenue earned #{@@reveune_earned}"
    return a 
  end

  def money_made(price)
    @@no_of_products*price
  end
end

class Gadget
  GADGETS = Hash.new{ |h, k| h[k] = {} }

  attr_reader :price, :weight, :height, :width

  def initialize(price, weight, height, width)
    @price, @weight, @height, @width = price, weight, height, width
  end

  def self.create(make, model, price, weight, height, width)
    if klass = GADGETS[make][model]
      klass.new(price, weight, height, width)
    else
      raise 'Gadget is not registered.'
    end
  end

  private

  def self.register_gadget(make, model)
    GADGETS[make][model] = self
  end

end

class IPhone5s < Gadget
  register_gadget :iPhone, 'iPhone5s'
end 

class IPhone6s < Gadget
  register_gadget :iPhone, 'iPhone6s'
end 

class IPhone6Plus < Gadget
  register_gadget :iPhone, 'iPhone6sPlus'
end 

测试它:

puts "here is your iphone5s"
p = AppleStore.new()
iphone5 = p.createiPhone('iPhone5s')
puts "here at the AppleStore"

输出:

here is your iphone5s
 A  iPhone5s that cost $ 99.00 weighing 4.87 ounces
 A store having sold 3 with revenue earned 198.0
here at the AppleStore