之前有看过《ruby设计模式》,不过渐渐的都忘记了。现在买了一个大话设计模式,看起来不是那么枯燥,顺便将代码用ruby实现了一下。
# -*- 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 #工厂类 class OperationFactory def self.create_operate(operate) case operate when ‘+‘ OperationAdd.new() when ‘-‘ OperationSub.new() when ‘*‘ OperationMul.new() when ‘/‘ OperationDiv.new() end end end oper = OperationFactory.create_operate(‘/‘) oper.number_a = 1 oper.number_b = 2 p oper.result
时间: 2024-10-16 01:19:58