依赖注入(DI) 是一种模式,其中对象从外部获取其 依赖关系(注入),而不是自己创建它们。它促进了松耦合、可测试性和灵活性——这是现代软件中一个基础的、广泛使用的模式。
依赖注入是什么
WITHOUT DI → a class CREATES its own dependencies (tightly coupled):
class OrderService { constructor() { this.db = new Database(); } } // hardcoded dependency
WITH DI → dependencies are PROVIDED (injected) from outside:
class OrderService { constructor(db) { this.db = db; } } // db is injected
→ the object doesn't create/control its dependencies → they're given to it
为什么 DI 很重要
✓ TESTABILITY → inject MOCKS/fakes in tests → test the class in isolation (the biggest win)
✓ LOOSE COUPLING → the class depends on an ABSTRACTION/interface, not a concrete class →
swap implementations easily
✓ FLEXIBILITY → change dependencies without changing the class (different configs, environments)
✓ EXPLICIT dependencies → constructor shows what the class needs (vs hidden creation)
✓ Separation of concerns → creation/wiring is separate from use
