Search This Blog

2023/08/31

Dependency Injection using property

 // Dependency class

class Dependency {
doAction() {
console.log("Dependency is performing an action.");
}
}

// Service class that relies on a dependency
class Service {
// Dependency is provided as a property
constructor() {
this.dependency = null;
}

setDependency(dependency) {
this.dependency = dependency;
}

doSomething() {
this.dependency.doAction();
}
}

// Creating instances and injecting dependencies
const dependency = new Dependency();
const service = new Service();

// Injecting the dependency as a property
service.setDependency(dependency);

service.doSomething();

No comments:

Post a Comment