Dependency injection come tecnica creazionale
Impari come la dependency injection completa i pattern creazionali spostando la costruzione degli oggetti dai consumer a un punto centrale di composizione.
Dependency injection come tecnica creazionale è una lezione Clean Architecture & Design Patterns in Practice gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Clean Architecture & Design Patterns in Practice, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Clean Architecture & Design Patterns in Practice include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
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.
Domande Frequenti
La lezione «Dependency injection come tecnica creazionale» è gratuita?
Sì — il testo completo di «Dependency injection come tecnica creazionale» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Clean Architecture & Design Patterns in Practice, passa a CoddyKit PRO. Il corso Clean Architecture & Design Patterns in Practice include 4 lezioni in totale.
Cosa imparerò in «Dependency injection come tecnica creazionale»?
Impari come la dependency injection completa i pattern creazionali spostando la costruzione degli oggetti dai consumer a un punto centrale di composizione. Eserciti Clean Architecture & Design Patterns in Practice con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare Clean Architecture & Design Patterns in Practice?
Non è richiesta alcuna esperienza precedente. Clean Architecture & Design Patterns in Practice su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Dependency injection come tecnica creazionale»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione Clean Architecture & Design Patterns in Practice?
Sì. Ogni lezione Clean Architecture & Design Patterns in Practice include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Singleton e Factory Method
- Abstract Factory e Builder
- Prototype e Object Pool
- Dependency injection come tecnica creazionale