Ruby中使用设计模式中的简单工厂模式和工厂方法模式(ruby模块和类的区别)怎么可以错过

随心笔谈2年前发布 编辑
160 0
🌐 经济型:买域名、轻量云服务器、用途:游戏 网站等 《腾讯云》特点:特价机便宜 适合初学者用 点我优惠购买
🚀 拓展型:买域名、轻量云服务器、用途:游戏 网站等 《阿里云》特点:中档服务器便宜 域名备案事多 点我优惠购买
🛡️ 稳定型:买域名、轻量云服务器、用途:游戏 网站等 《西部数码》 特点:比上两家略贵但是稳定性超好事也少 点我优惠购买


# -*- 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

© 版权声明

相关文章