定义:单例是只能有一个实例的类,并且为那个实例提供全局的访问。
单例模式的实现步骤:
1.采用一个类变量来保存仅有的一个类的变量。
2.需要一个类方法用来返回这个单例实例。
3.将类的new方法设置为私有方法
#代码实现
class SimpleLogger
#initialize方法必须放在第一位
def initialize
@log = File.open("./file_demo.txt", "w+")
end
#通过类方法来获取实例化对象,也是类变量
def self.instance
@@instance ||= SimpleLogger.new
end
def error(msg)
@log.puts(msg)
@log.flush
end
def warning(msg)
@log.puts(msg)
@log.flush
end
#通过private_class_method方法来设置实例化对象只有一个,外部不能调用SimpleLogger.new方法
private_class_method :new
end
#SimpleLogger.instance
SimpleLogger.instance.error("this is the error")
SimpleLogger.instance.warning("this is the warning")
通过Ruby中自带的标准模块Singleton来实现单例模式,这个Singleton实现的工作包括,创建类变量,初始化单例实例,创建类级别的instance方法,以及将new设为私有方法。实现代码如下所示,和上面的自定义的singleton的区别在于后者属于惰性的单例,惰性的单例是指只有在用到的时候才使用单例,而上面自定义的单例中在需要之前已经创建单例。
require 'singleton'
class SimpleLogger
include Singleton
def initialize
@log = File.open("./file_demo.txt", "w+")
end
def error(msg)
@log.puts(msg)
@log.flush
end
def warning(msg)
@log.puts(msg)
@log.flush
end
private_class_method :new
end
#SimpleLogger.instance
SimpleLogger.instance.error("this is the error")
SimpleLogger.instance.warning("this is the warning")