繁体   English   中英

Ruby中的单例与单态模式

[英]Singleton vs. Monostate Pattern in Ruby

假设一个类需要加载一个外部库,这需要花费一些时间才能加载,因此应该只加载一次。 两种自然的解决方案是使用单例模式或单态模式。 在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强制执行behavior of a singleton without the structure of the monostate

您可能会发现仍然需要实例数据的情况。 因此,单州制会更好。 您可以创建实例,使用影响实例数据的方法,并且仍然可以访问静态数据。 单身人士不能拥有实例数据。

此外,如果计划从单例派生类,并且希望这些类为单例,则更好的选择是单态。 这是因为从单态派生的所有类都是单态。 默认情况下,派生为单例类的类不是单例。 您必须将静态方法和属性添加到每个派生类。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM