依赖注入
代码示例
class WheelHub {
constructor(size, brand, material) {}
}
class Tire {
constructor(size, brand, material) {}
}
class Wheel {
constructor(size, wheelHubBrand, wheelHubMaterial, tireBrand, tireMaterial) {
this.wheelHub = new WheelHub(size, wheelHubBrand, wheelHubMaterial);
this.tire = new Tire(size, tireBrand, tireMaterial);
}
}
// 使用依赖注入,将依赖实例注入
class DIWheel {
constructor(wheelHub, tire) {
if (wheelHub.size !== tire.size) {
throw new Error('轮毂和轮胎尺寸不匹配');
}
this.wheelHub = wheelHub;
this.tire = tire;
}
}
// 对象之间的依赖关系更加灵活和可配置
const wheelHub1 = new WheelHub(19, '轮毂品牌1', '材料1');
const wheelHub2 = new WheelHub(19, '轮毂品牌2', '材料2');
const tire1 = new Tire(19, '车胎品牌', '光头胎');
const tire2 = new Tire(19, '车胎品牌', '雨胎');
// 灵活的基于组合创建了 4 轮胎实例
const wheel1 = new DIWheel(wheelHub1, tire1);
const wheel2 = new DIWheel(wheelHub1, tire2);
const wheel3 = new DIWheel(wheelHub2, tire1);
const wheel4 = new DIWheel(wheelHub2, tire2);延展
最后更新于