Skip to content

Instantly share code, notes, and snippets.

@ZhouMeichen
Last active December 27, 2015 01:19
Show Gist options
  • Save ZhouMeichen/7244473 to your computer and use it in GitHub Desktop.
Save ZhouMeichen/7244473 to your computer and use it in GitHub Desktop.
单例方法和实例方法(Singleton method and Instance method)

单例方法和实例方法(Singleton method and Instance method)

一、单例方法(Singleton method)

1、介绍

单例方法是某个具体实例对象的特有方法,只属于该实例对象。在Ruby中一切都是对象,所以类方法(Class method)也是一种特殊的单例方法,是某个具体类的特有方法。

2、实现

# 第一种:普通
Class SingletonExample
  def info
    puts 'This is example.'
  end
end

obj1 = SingletonExample.new
obj2 = SingletonExample.new

def obj1.info
  puts 'This is info of obj1.'
end

def obj1.singletonmethod
  puts 'This is singleton method of obj1.'
end

# result
obj1.info  # => 'This is info of obj1.'
obj1.singletonmethod # => 'This is singleton method of obj1.'
obj2.info # => 'This is example.'
obj2.singletonmethod # => Error

# 第二种:单例类
Class SingletonExample
  def info
    puts 'This is example.'
  end
end

obj1 = SingletonExample.new
obj2 = SingletonExample.new

Class << obj1 # obj1's singleton class
  def info
    puts 'This is info of obj1.'
  end

  def singletonmethod
    puts 'This is singleton method of obj1.'
  end
end

# result
obj1.info # => 'This is info of obj1.'

# 第三种:instance_eval
Class SingletonExample
  def info
    puts 'This is example.'
  end
end

obj1 = SingletonExample.new
obj2 = SingletonExample.new

obj1.instance_eval do
  self # => obj1
  #current class => ojb1's singleton class
  
  def info # obj1's singleton method
    puts 'This is info of obj1.'
  end
end

# result
obj1.info # => 'This is info of obj1.'
obj2.info # => 'This is example.'

二、实例方法(Instance method)

1、介绍

实例方法是属于类的每个实例对象的方法,每个实例对象都可以调用实例方法。

2、实现

# 第一种:普通
Class InstanceExample
  def info
    puts 'This is example.'
  end
end

# 第二种:class_eval
Class InstanceExample
  def info
    puts 'This is example.'
  end
end

InstanceExample.class_eval do
  self # => InstanceExample
  # current class => InstanceExample's singleton class
  
  def info
    puts 'This is info of InstanceExample.'
  end
end

obj1 = InstanceExample.new
obj2 = InstanceExample.new

# result
obj1.info # => 'This is info of InstanceExample.'
obj2.info # => 'This is info of InstanceExample.'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment