我正在学习设计模式。您如何看待它是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