봄맞이 세일
싱글턴

러스트로 작성된 싱글턴

싱글턴은 같은 종류의 객체가 하나만 존재하도록 하고 다른 코드의 해당 객체에 대한 단일 접근 지점을 제공하는 생성 디자인 패턴입니다.

싱글턴은 전역 변수들과 거의 같은 장단점을 가지고 있습니다: 매우 편리하나 코드의 모듈성을 깨뜨립니다.

싱글턴에 의존하는 클래스를 다른 콘텍스트에서 사용하려면 싱글턴도 다른 콘텍스트로 전달해야 합니다. 대부분의 경우 이 제한 사항은 유닛 테스트를 생성하는 동안 발생합니다.

Rust specifics

By definition, Singleton is a global mutable object. In Rust this is a static mut item. Thus, to avoid all sorts of concurrency issues, the function or block that is either reading or writing to a mutable static variable should be marked as an unsafe block.

For this reason, the Singleton pattern can be percieved as unsafe. However, the pattern is still widely used in practice. A good read-world example of Singleton is a log crate that introduces log!, debug! and other logging macros, which you can use throughout your code after setting up a concrete logger instance, such as env_logger. As we can see, env_logger uses log::set_boxed_logger under the hood, which has an unsafe block to set up a global logger object.

  • In order to provide safe and usable access to a singleton object, introduce an API hiding unsafe blocks under the hood.
  • See the thread about a mutable Singleton on Stackoverflow for more information.

Starting with Rust 1.63, Mutex::new is const, you can use global static Mutex locks without needing lazy initialization. See the Singleton using Mutex example below.

다른 언어로 작성된 싱글턴

C#으로 작성된 싱글턴 C++로 작성된 싱글턴 Go로 작성된 싱글턴 자바로 작성된 싱글턴 PHP로 작성된 싱글턴 파이썬으로 작성된 싱글턴 루비로 작성된 싱글턴 스위프트로 작성된 싱글턴 타입스크립트로 작성된 싱글턴