收藏本站 收藏本站
积木网首页 - 软件测试 - 常用手册 - 站长工具 - 技术社区
首页 > ruby > 正文

首页 - PHP - 数据库 - 操作系统 - 游戏开发 - JS - Android - MySql - Redis - MongoDB - Win8 - Shell编程 - DOS命令 - jQuery - CSS样式 - Python - Perl

Access - Oracle - DB2 - SQLServer - MsSql2008 - MsSql2005 - Sqlite - PostgreSQL - node.js - extjs - JavaScript vbs - Powershell - 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

这样写的好处是降低耦合。
比如增加一个开根号运算的时候,只需要在工厂类中添加一个分支,并新建一个开根号类,不会去动到其他的类。

工厂方法模式:

# -*- 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使用设计模式中的代理模式与装饰模式的代码实例
代理模式需求:小明让小李替他追小丽(送洋娃娃,送花,送巧克力)没有代理的代码:#-*-encoding:utf-8-*-#追求者类classPursuitattr_accessor:mmdefinitialize(mm)@mm=

Ruby设计模式编程之适配器模式实战攻略
适配器模式适配器模式可以用于对不同的接口进行包装以及提供统一的接口,或者是让某一个对象看起来像是另一个类型的对象。在静态类型的编程语

详解Ruby设计模式编程中对单例模式的运用
简介单例模式是设计模式中最简单的形式之一。这一模式的目的是使得类的一个对象成为系统中的唯一实例。要实现这一点,可以从客户端对其进行实

本周排行

更新排行

强悍的草根IT技术社区,这里应该有您想要的!
Copyright © 2010 Gimoo.Net. All Rights Rreserved  京ICP备05050695号