Ruby中使用设计模式中的简单工厂模式和工厂方法模式

时间:2021-05-22

之前有看过《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 endend#加法类class OperationAdd < Operation def result number_a + number_b endend#减法类class OperationSub < Operation def result number_a - number_b endend#乘法类class OperationMul < Operation def result number_a * number_b endend#除法类class OperationDiv < Operation def result raise '除数不能为0' if number_b == 0 number_a / number_b endend#工厂类class OperationFactory def self.create_operate(operate) case operate when '+' OperationAdd.new() when '-' OperationSub.new() when '*' OperationMul.new() when '/' OperationDiv.new() end endendoper = OperationFactory.create_operate('/')oper.number_a = 1oper.number_b = 2p 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 endend#加法类class OperationAdd < Operation def result number_a + number_b endend#减法类class OperationSub < Operation def result number_a - number_b endend#乘法类class OperationMul < Operation def result number_a * number_b endend#除法类class OperationDiv < Operation def result raise '除数不能为0' if number_b == 0 number_a / number_b endendmodule FactoryModule def create_operation endend#加法工厂class AddFactory include FactoryModule def create_operation OperationAdd.new end end#减法工厂class SubFactory include FactoryModule def create_operation OperationSub.new endend#乘法工厂class MulFactory include FactoryModule def create_operation OperationMul.new end end#除法工厂class DivFactory include FactoryModule def create_operation OperationDiv.new end endfactory = AddFactory.newoper = factory.create_operationoper.number_a = 1oper.number_b = 2p oper.result

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

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章