这篇文章主要介绍了Ruby中使用设计模式中的简单工厂模式和工厂方法模式的示例,这两种模式经常被用于Ruby on Rails开发的结构设计中,需要的朋友可以参考下
之前有看过《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
相比于简单工厂模式,这里的变化是移除了工厂类,取而代之的是具体的运算工厂,分别是加法工厂、减法工厂、乘法工厂和除法工厂。
沃梦达教程
本文标题为:Ruby中使用设计模式中的简单工厂模式和工厂方法模式


猜你喜欢
- R语言-如何切换科学计数法和更换小数点位数 2022-11-23
- Golang http.Client设置超时 2023-09-05
- R语言绘图数据可视化pie chart饼图 2022-12-10
- Ruby的字符串与数组求最大值的相关问题讨论 2023-07-22
- Ruby on Rails在Ping ++ 平台实现支付 2023-07-22
- Ruby 迭代器知识汇总 2023-07-23
- 汇编语言程序设计之根据输入改变屏幕颜色的代码 2023-07-06
- Swift超详细讲解指针 2023-07-08
- R语言关于二项分布知识点总结 2022-11-30
- Go Web开发进阶实战(gin框架) 2023-09-06