English
[1Day-1CS] Singleton Patterns

[1Day-1CS] Singleton Patterns

1 day 1CS, a quick recap of the singleton pattern

What are design patterns?

A problem exists when designing a program → Create a convention to solve it by using interrelationships between objects, etc.

Singleton Pattern

  • One class = one instance

  • We could create multiple separate instances per class, but we don't, we use only one

  • Usually used for DB modules

  • Productivity ↑, dependency ↓

Disadvantages of the Singleton Pattern

  • Possibility of issues when running unit tests during Test Driven Development (TDD)

Difficult to create an independent instance for each test due to the highly dependent nature of the singleton pattern

Dependency Injection

  • A way to address the disadvantages of the singleton pattern's strong coupling between modules.

  • Instead of the main module directly giving dependencies to other submodules, it injects dependencies indirectly through a dependency injector (decoupling)

Advantages

Easier to replace modules, Easier to test & migrate, Consistency in dependency orientation, Easier to reason about application, Clarity of relationships, etc.

Cons

Modules are more decoupled → Increased complexity due to increased number of classes, runtime penalty

Principles of Dependency Injection

  • Parent module does not import anything from child modules

  • Both must rely on an abstraction + Abstraction does not depend on details

댓글 작성

게시글에 대한 의견을 남겨 주세요.

댓글 0