154人参与 • 2024-05-19 • Ruby
之前有看过《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
这样写的好处是降低耦合。
比如增加一个开根号运算的时候,只需要在工厂类中添加一个分支,并新建一个开根号类,不会去动到其他的类。
工厂方法模式:
# -*- 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
相比于简单工厂模式,这里的变化是移除了工厂类,取而代之的是具体的运算工厂,分别是加法工厂、减法工厂、乘法工厂和除法工厂。
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论