클래스가로드하는 데 시간이 걸리므로 한 번만로드해야하는 외부 라이브러리를로드해야한다고 가정합니다. 이것에 대한 두 가지 자연적인 해결책은 싱글 톤 패턴이나 모노 스테이트 패턴을 사용하는 것입니다. 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)
이후 번째 구문 훨씬 청소기 루비 싱글 톤을 사용하는 장점이있는입니까?
'require' 메소드는 라이브러리를로드하고 두 번 이상로드되지 않도록합니다. – steenslag
나는 루비가 아닌 라이브러리를 특별히 언급했다. 단지 require만으로는 처리 할 수 없다. 제안한 것이 같은 것을 달성하는 세 번째 방법을 가리키고있다. 'class Parser; @@ parser = load_external_library; def self.parse (sentence); @@ parser.parse (sentence); 종료; end' ... 다른 파일에서 'require'parser''. 이것은 모노 스테이트와 유사하지만 사용자 코드가 이제는 한 번만 요구할 책임이 있으며 이는 예상보다 까다로울 수 있습니다 (http://ghouston.blogspot.com/2007/05/ruby-require-idiom.html).). 이견있는 사람? – user2398029