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
相关推荐
咩图1 天前
Sketchup软件二次开发+Ruby+VisualStudioCode
java·前端·ruby
开开心心就好2 天前
开源免费高速看图工具,支持漫画大图秒开
linux·运维·服务器·安全·ruby·symfony·1024程序员节
芒鸽2 天前
基于 lycium 适配鸿蒙版 Ruby 的解决方案
华为·ruby·harmonyos
Knight_AL3 天前
线程池满了怎么办?用 RabbitMQ 做任务补偿不丢失
分布式·rabbitmq·ruby
小北方城市网3 天前
RabbitMQ 生产级实战:可靠性投递、高并发优化与问题排查
开发语言·分布式·python·缓存·性能优化·rabbitmq·ruby
h7ml7 天前
基于 RabbitMQ 构建异步化淘客订单处理流水线:解耦、削峰与失败重试
分布式·rabbitmq·ruby
一点事13 天前
windows:安装rabbitMQ
windows·rabbitmq·ruby
Knight_AL14 天前
RabbitMQ + Flink 为什么必然会重复?以及如何用 seq 做稳定去重
flink·rabbitmq·ruby
alonewolf_9916 天前
RabbitMQ高级功能全面解析:队列选型、死信队列与消息分片实战指南
分布式·消息队列·rabbitmq·ruby
m0_7482523820 天前
Ruby 模块(Module)的基本概念
开发语言·python·ruby