Ruby 之方法委托

ruby 方法委托的优点在于,可以将多个不同实例(或类)的方法组织在一起,然后进行统一调用,方便各类方法的统一管理。比如下边示例中的 color 和 username,本来是不同类里边的方法,但最后都可以统一使用 Man 的实例进行调用。

实例方法委托

ruby 复制代码
require 'forwardable'

class Person
  attr_accessor :name, :sex # attr_accessor相当于attr_reader和attr_writer的合集,实际上是在定义类成员变量的时候就给他定义了一个get和set方法。

  def initialize(name, sex)
    @name, @sex = name, sex
  end

  def username
    @name
  end
end

class Color
  attr_accessor :color

  def initialize(color)
    @color = color
  end
end

class Man
  extend Forwardable

  def_delegators :@person, :username, :sex # 将 username 和 sex 方法委托给 @person,在 Man 实例上调用 username 方法相当于调用 @person 的 username 方法
  def_delegators :@color, :color # 将 color 方法委托给 @color,在 Man 实例上调用 color 方法相当于调用 @color 的 color 方法

  def initialize()
    @person = Person.new("Looking", "male")
    @color = Color.new("white")
  end
end

man = Man.new
puts man.username # Looking
puts man.sex # male
puts man.color # white

类方法委托

ruby 复制代码
require 'forwardable'

class Person
  def initialize()
  end

  def self.nickname
    self.name + " nickname"
  end
end

class Man
  extend SingleForwardable

  def_delegators :Person, :nickname # 将 nickname 类方法委托给 Person,在 Man 类中直接调用 nickname 类方法相当于调用 Person 的 nickname 方法

  def initialize()
  end
end

puts Man.nickname # Person nickname
相关推荐
嘻嘻仙人3 天前
SHA-256算法详解——Github工程结合示例和动画演示
区块链·ruby·哈希算法·sha-256
kk_stoper3 天前
使用Ruby接入实时行情API教程
java·开发语言·javascript·数据结构·后端·python·ruby
Baklib梅梅5 天前
Ruby大会演讲实录:Baklib 如何用 AI 重构内容管理赛道
ruby on rails·前端框架·ruby
幼稚园的山代王7 天前
RabbitMQ 4.1.1初体验-队列和交换机
分布式·rabbitmq·ruby
幼稚园的山代王8 天前
RabbitMQ 4.1.1初体验
分布式·rabbitmq·ruby
一路向北North8 天前
RabbitMQ简单消息监听和确认
分布式·rabbitmq·ruby
一路向北North8 天前
使用reactor-rabbitmq库监听Rabbitmq
分布式·rabbitmq·ruby
旷世奇才李先生9 天前
Ruby 安装使用教程
开发语言·后端·ruby
空白6669 天前
搭建VirtualBox-6+vagrant_2+docker+mysql5.7的步骤
docker·ruby·vagrant
大熊猫侯佩19 天前
ruby、Python 以及 Swift 语言关于 “Finally” 实现的趣谈
python·ruby·swift