Ruby中使用设计模式中的简单工厂模式和工厂方法模式(ruby模块和类的区别)怎么可以错过

随心笔谈11个月前发布 admin
97 0


# -*- encoding: utf-8 -*-

#运算类
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

© 版权声明

相关文章