Have seen "Ruby design mode" before, but gradually forgot. Now bought a big talk design pattern, it does not look so boring, by the way the code in Ruby implementation.
Simple Factory mode:
#-*-Encoding:utf-8-*-#运算类 class Operation Attr_accessor:number_a,:number_b de
F Initialize (number_a = nil, Number_b = nil) @number_a = number_a @number_b = number_b End def result 0 end #加法类 class Operationadd < Operation def result number_a + Number_b end #减法类 class Operationsub < Operatio N def result Number_a-number_b end #乘法类 class Operationmul < Operation def result number_a * Number_b en D End #除法类 class Operationdiv < Operation def result raise ' divisor cannot be 0 ' if Number_b = = 0 Number_a/number_b end en D #工厂类 class Operationfactory def self.create_operate (operate) case operate when ' + ' operationadd.new () '- ' Operationsub.new () when ' * ' operationmul.new () while '/' operationdiv.new () end End oper = Operation Factory.create_operate ('/') oper.number_a = 1 Oper.number_b = 2 p oper.result
The advantage of this writing is the reduction of coupling.
For example, to add a square root operation, you need only a branch in the factory class, and a new open square root class, will not move to other classes.
Factory method Mode:
#-*-Encoding:utf-8-*-#运算类 class Operation Attr_accessor:number_a,:number_b def initialize (number_a = nil, numb Er_b = nil) @number_a = number_a @number_b = number_b End def result 0 End #加法类 class Operationadd < Op Eration def result number_a + Number_b end #减法类 class Operationsub < Operation def result Number_a-number _b End #乘法类 Class Operationmul < Operation def result number_a * Number_b end #除法类 class Operationdiv &L T Operation def result raise ' divisor cannot be 0 ' if Number_b = = 0 Number_a/number_b End Module Factorymodule def create _operation end #加法工厂 class addfactory include Factorymodule def create_operation Operationadd.new End #减 French factory class subfactory include Factorymodule def create_operation operationsub.new End #乘法工厂 class mulfactory in
Clude factorymodule def create_operation operationmul.new end #除法工厂 class divfactory include Factorymodule
def create_operation Operationdiv.new End factory = addfactory.new Oper = factory.create_operation oper.number_a = 1 Oper.number_b = 2
P Oper.result
Compared to the simple factory model, the change here is to remove the factory class and replace it with a specific computing plant, the addition plant, the subtraction plant, the multiplication plant, and the Division factory.