Ruby上的FactoryMethod模式

时间:2017-04-17 19:59:12

标签: ruby oop solid-principles factory-method

我正在学习设计模式。您如何看待它是FactoryMethod模式的合适示例?

有单位及其子类:士兵和博士。他们可以以某种方式问候。还有UnitFactory,SoldierFactory和DoctorFactory。他们按照单位生产。

class Unit
  class GreetError < StandardError; end

  def greet; raise GreetError; end
end

class Soldier < Unit
  def greet; 'I am a soldier'; end
end

class Doctor < Unit
  def greet; 'I am a doctor'; end
end

class UnitFactory
  class CreateUnitError < StandardError; end

  def create_unit; raise CreateUnitError; end
end

class SoldierFactory < UnitFactory
  def create_unit; Soldier.new; end
end

class DoctorFactory < UnitFactory
  def create_unit; Doctor.new; end
end

class Army
  attr_reader :unit_factory, :count, :units

  def initialize(unit_factory, count)
    @unit_factory = unit_factory
    @count = count
    @units = []

    gather
  end

  def gather
    count.times { units << unit_factory.create_unit }
  end

  def greet
    units.map { |unit| unit.greet }
  end
end

0 个答案:

没有答案