Внедрение зависимостей как порождающий приём
Узнайте, как внедрение зависимостей дополняет порождающие шаблоны, перенося создание объектов из потребителей в единую точку композиции
«Внедрение зависимостей как порождающий приём» — бесплатный урок Clean Architecture & Design Patterns in Practice на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Clean Architecture & Design Patterns in Practice, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Clean Architecture & Design Patterns in Practice содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Why Another Creational Approach?
Classic creational patterns like Factory and Builder centralize how objects are built. Dependency Injection (DI) centralizes where they are wired together.
- A class no longer creates its own collaborators.
- Instead, collaborators are supplied from outside.
This is the natural endpoint of the creational journey: removing the new keyword from business logic entirely.
The Problem DI Solves
Consider a service that builds its own dependency:
The service is now hard-wired to a concrete class. You cannot swap it for a test double or an alternative implementation without editing the service.
class ReportService {
private final MySqlDatabase db = new MySqlDatabase();
void run() { db.query("..."); }
}Constructor Injection
The most common and recommended form: dependencies arrive through the constructor.
- The class declares what it needs, not how to get it.
- Dependencies become
finaland guaranteed present.
class ReportService {
private final Database db;
ReportService(Database db) { this.db = db; }
void run() { db.query("..."); }
}Inversion of Control
DI is a concrete technique for the broader principle of Inversion of Control (IoC): the flow of object creation is inverted away from the consumer.
The consumer no longer asks I will build my tools; instead it says give me what I need. A higher layer decides the wiring.
The Composition Root
All wiring happens in one place near the program entry point, called the composition root.
This is where concrete classes are finally chosen and assembled into the object graph.
public static void main(String[] args) {
Database db = new MySqlDatabase();
ReportService service = new ReportService(db);
service.run();
}DI vs Factory
They are complementary, not competitors:
- A Factory decides which concrete object to build at runtime.
- DI passes already-built objects into consumers.
A composition root often uses factories to produce the objects it then injects.
Setter and Method Injection
Two other forms exist for optional dependencies:
- Setter injection: a dependency is set after construction.
- Method injection: a dependency is passed to a single method call.
Prefer constructor injection for required collaborators; reserve these for truly optional ones.
class Logger { void log(String m) {} }
class Job {
private Logger logger;
void setLogger(Logger l) { this.logger = l; }
}DI Containers
Frameworks like Spring or Guice provide a DI container that auto-resolves the object graph based on registered types.
The container is your composition root, automated. But the principle is identical: construction is centralized and consumers stay clean.
Testability Benefit
Because dependencies are injected, tests can pass mocks or fakes directly.
class FakeDatabase implements Database {
public void query(String s) { /* record call */ }
}
// in test
ReportService s = new ReportService(new FakeDatabase());Avoiding the Service Locator Anti-Pattern
A tempting shortcut is a global service locator that classes call to fetch dependencies.
This hides dependencies again and reintroduces coupling. Prefer explicit injection so a class signature truthfully declares everything it needs.
Guidelines for Clean Construction
- Push
newto the composition root. - Depend on abstractions, inject implementations.
- Use constructor injection by default.
- Keep constructors free of logic; only assign fields.
Quick Check
Test your understanding of dependency injection.
Recap
You learned that Dependency Injection extends the creational toolkit by removing object construction from consumers.
- Constructor injection is the default form.
- Wiring lives in the composition root.
- DI complements factories and dramatically improves testability.
You now have a complete picture of creating objects cleanly.
Часто задаваемые вопросы
Урок «Внедрение зависимостей как порождающий приём» бесплатный?
Да — полный текст урока «Внедрение зависимостей как порождающий приём» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Clean Architecture & Design Patterns in Practice, подпишись на CoddyKit PRO. Курс Clean Architecture & Design Patterns in Practice содержит 4 уроков всего.
Чему я научусь в уроке «Внедрение зависимостей как порождающий приём»?
Узнайте, как внедрение зависимостей дополняет порождающие шаблоны, перенося создание объектов из потребителей в единую точку композиции Ты практикуешь Clean Architecture & Design Patterns in Practice с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Clean Architecture & Design Patterns in Practice?
Предыдущий опыт не требуется. Clean Architecture & Design Patterns in Practice на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Внедрение зависимостей как порождающий приём»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Clean Architecture & Design Patterns in Practice?
Да. Каждый урок Clean Architecture & Design Patterns in Practice включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Одиночка и фабричный метод
- Абстрактная фабрика и строитель
- Прототип и пул объектов
- Внедрение зависимостей как порождающий приём