代码示例

class Operation
  attr_accessor :number_a, :number_b

  def initialize(number_a=nil, number_b=nil)
    @number_a = number_a
    @number_b = number_b
  end

  def result
    0
  end
end

class OperationAdd < Operation
  def result
    number_a + number_b
  end
end

class OperationSub < Operation
  def result
    number_a - number_b
  end
end

class OperationMul < Operation
  def result
    number_a * number_b
  end
end

class OperationDiv < Operation
  def result
    raise "除数不能为0" if number_b == 0
    number_a / number_b
  end
end

#工厂类
module FactoryModule
  def create_operation
  end
end

class AddFactory
  include FactoryModule

  def create_operation
    OperationAdd.new
  end
end

class SubFactory
  include FactoryModule

  def create_operation
    OperationSub.new
  end
end

class MulFactory
  include FactoryModule

  def create_operation
    OperationMul.new
  end
end

class DivFactory
  include FactoryModule

  def create_operation
    OperationDiv.new
  end
end

factory = AddFactory.new
oper = factory.create_operation
oper.number_a = 1
oper.number_b = 2
p oper.result

相比简单工厂模式,工厂方法模式移除了工厂类,取而代之的是具体的运算工厂,分别是加法工厂、减法工厂、乘法工厂和除法工厂。

工厂方法模式是将决定使用哪个类放在子类中的用法,上面中使用module的形式来实现代码复用,其实也可以用父类的形式,使用父类和子类的形式是比较典型和直接的工厂方法模式。

#其他代码相同,改写module成为父类,并且其他工厂类都是该父类的子类
class Factory
  def create_operation
  end
end

class AddFactory < Factory
  def create_operation
    OperationAdd.new
  end
end

class SubFactory < Factory
  def create_operation
    OperationSub.new
  end
end

class MulFactory < Factory
  def create_operation
    OperationMul.new
  end
end

class DivFactory < Factory
  def create_operation
    OperationDiv.new
  end
end

factory = AddFactory.new
oper = factory.create_operation
oper.number_a = 1
oper.number_b = 2
p oper.result

results matching ""

    No results matching ""