在Ruby中,可以使用Singleton模块来实现单例模式。下面是一个使用Singleton模块的例子:
require 'singleton'class MySingleton include Singleton def initialize @counter = 0 end def increase_counter @counter += 1 end def get_counter @counter endend# 使用单例模式创建对象singleton_1 = MySingleton.instancesingleton_2 = MySingleton.instancesingleton_1.increase_countersingleton_2.increase_counterputs singleton_1.get_counter # 输出 2puts singleton_2.get_counter # 输出 2在上面的例子中,MySingleton类使用include Singleton来包含Singleton模块,从而确保只有一个实例被创建。通过调用MySingleton.instance可以获取该类的唯一实例。




