我正在使用Gadget
类,其中包含initialize
方法(品牌,型号,价格,重量,高度,宽度)。 Gadget
有三个子类:IPhone5s
,IPhone6s
和IPhone6
。我需要有关继承方法createiPhone
的帮助。
我正在努力在方法createiPhone
中打印其他子类。我想在用户创建iPhone6s
时使用iPhone6Plus
和iPhone6s
,然后将价格输出到方法createiPhone
中。关于如何处理这个问题的任何建议都是有用的。
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
答案 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