Ruby中的单例模式怎么实现
在Ruby中,可以使用Singleton
模块来实现单例模式。下面是一个使用Singleton
模块的例子:
require 'singleton'class MySingletoninclude Singletondef initialize@counter = 0enddef increase_counter@counter += 1enddef get_counter@counterendend# 使用单例模式创建对象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
可以获取该类的唯一实例。