假设一个类需要加载一个外部库,它需要一些时间来加载,因此应该只加载一次。两种自然的解决方案是使用单例模式或单态模式。在 Ruby 的这个特定上下文中,这两种解决方案有什么优势吗?
例如:
# Using a Singleton class
require 'singleton'
class Parser
include Singleton
def initialize
@parser = load_external_library
end
def parse(sentence)
@parser.parse(sentence)
end
end
# Then calling using...
Parser.instance.parse(sentence)
对比:
# Using a Monostate class
class Parser
def self.parse(sentence)
@@parser ||= load_external_library
@@parser.parse(sentence)
end
end
# Then calling using...
Parser.parse(sentence)
既然第二种语法更简洁,那么在 Ruby 中使用 Singleton 有什么优势吗?
最佳答案
单例模式在结构上强化了这样一个事实,即您可以 never have more than one instance of a class at a time
,对于开发人员来说很明显他们正在处理单例。
单一国家执行 behavior of a singleton without the structure of the monostate
.
您可能会发现仍然需要实例数据的情况。因此,单一国家会更好。您可以创建实例,使用方法来影响实例数据并且仍然可以访问静态数据。对于单例,您不能拥有实例数据。
此外,如果您计划从单例派生类并且您希望这些类是单例,那么更好的选择是单态。那是因为从单态派生的所有类都是单态的。默认情况下,类派生单例类不是单例。您必须将静态方法和属性添加到每个派生类。
关于ruby - Ruby 中的单例模式与单态模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8698247/