在Ruby中,单例模式可以通过使用模块或类来实现。这里有两种方法来初始化单例模式:
方法1:使用模块
module Singleton
def self.included(base)
base.class_eval do
@instance = nil
def self.instance
@instance ||= new
end
def self.new(*args, &block)
raise "Singleton class can't be instantiated"
end
end
end
end
class MyClass
include Singleton
def initialize(name)
@name = name
end
end
my_instance1 = MyClass.instance
my_instance2 = MyClass.instance
puts my_instance1.object_id == my_instance2.object_id # 输出 true,表示两个实例是同一个对象
方法2:使用类变量
class SingletonClass
@@instance = nil
def self.instance
@@instance ||= new
end
def self.new(*args, &block)
raise "Singleton class can't be instantiated"
end
end
class MyClass < SingletonClass
def initialize(name)
@name = name
end
end
my_instance1 = MyClass.instance
my_instance2 = MyClass.instance
puts my_instance1.object_id == my_instance2.object_id # 输出 true,表示两个实例是同一个对象
这两种方法都可以实现单例模式,确保一个类只有一个实例,并提供一个全局访问点。