Software engineeringLesson 2 of 3 in the course Design patterns

Singleton Pattern: Initialization, Concurrency, and Trade-offs

5 flashcards · 5 quiz questions · 5 match pairs · 5 fill-in sentences · English

Lesson progress
0 / 5

Your progress is kept in this browser only.Sign up to save it

Summary

The singleton pattern restricts a class to a single instance and provides a way to access that instance. This lesson explains what the pattern is designed to do, why developers use it, and where it commonly appears.

In object-oriented programming, a singleton is a design pattern that ensures a class has only one instance and provides access to that instance. It is one of the well-known Gang of Four design patterns, which describe recurring solutions to software design problems.

All flashcards

What is the singleton pattern?
It is a design pattern that restricts a class to one instance and provides a way to access that instance.
How can a singleton differ from a global variable?
A singleton can avoid occupying the global namespace and may delay allocating and initializing its object until it is needed.
Why might a logging component use a singleton?
It can offer many objects a uniform access point for writing messages to one shared logging destination.
What is a facade object?
An object that provides a simplified interface to a subsystem; one facade may be sufficient for an application.
What does singleton mean as a dependency injection service lifetime?
The dependency injection container creates one instance of a service and shares that same instance throughout the application. The service can be an ordinary class rather than a class with a private constructor and static instance method.

Quiz questions

  1. When does an eagerly instantiated singleton create its instance?Answer: During static initialization, before the access method is first called.
  2. What thread-safety guarantee does C++11 provide for a function-local static used in the Meyers singleton?Answer: Its initialization is thread-safe without manual locks.
  3. Why can a globally accessible singleton make unit testing harder?Answer: Code that looks it up directly can acquire hidden dependencies.
  4. What does dependency injection focus on, rather than requiring a class to decide how many instances exist?Answer: How dependencies are passed to an object.
  5. What design concern arises because a singleton both performs its normal work and enforces uniqueness?Answer: It can conflict with the single-responsibility principle.

Based on the Wikipedia article Singleton pattern, licensed CC BY-SA 4.0. Adapted into a summary, flashcards and quizzes.

All Software engineering lessons