Ruby实现设计模式背景
此前曾阅读过《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
这种写法的主要优势在于降低了系统间的耦合度。例如,当需要增加开根号运算时,仅需在工厂类中增加相应的分支判断,并新建对应的开根号类即可,无需修改其他现有类的代码。
工厂方法模式结构变化
工厂方法模式是对简单工厂模式的进一步抽象和扩展。
工厂方法模式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
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
与简单工厂模式相比,工厂方法模式移除了单一的通用工厂类,转而定义了一系列具体的工厂类,分别负责创建加法、减法、乘法和除法等特定运算对象。