// 引擎 export class Engine { public cylinders = '引擎发动机1'; } // 轮胎 export class Tires { public make = '品牌'; } export class Car { public engine: Engine; public tires: Tires; public description = 'No DI'; constructor() { this.engine = new Engine(); this.tires = new Tires(); } // Method using the engine and tires drive() { return `${this.description} car with ` + `${this.engine.cylinders} cylinders and ${this.tires.make} tires.`; } }
// 轮胎 export class Tires { public make = '品牌'; } export class Tires1 extends Tires { public make = '品牌1'; } export class Tires2 extends Tires { public make = '品牌2'; } export class Car { //。。。。。。其他代码省略。。。。。。。 public tires: Tires; constructor() { this.tires = new Tires1(); } }
export class Engine { public cylinders = '引擎发动机1'; } export class Tires { public make = '品牌'; } export class Tires1 extends Tires { public make = '品牌1'; } export class Tires2 extends Tires { public make = '品牌2'; } export class Car { public description = 'DI'; // 通过构造函数注入Engine和Tires constructor(public engine: Engine, public tires: Tires) {} // Method using the engine and tires drive() { return `${this.description} car with ` + `${this.engine.cylinders} cylinders and ${this.tires.make} tires.`; } }
在以上代码中,通过往构造函数中传入engine和tires来创建Car,**::Car类不再亲自创建engine和tires,而是消费它们::**,此时最大的好处就是engine和tires与Car解除了强耦的关系。在new Car的时候,可以传入任何类型的Engine和Tires,即 let car = new Car(new Engine(),new Tires());
解决问题1:如果有一天对引擎进行升级,代码如下:
1 2 3 4 5 6
export class Engine { public cylinders = ''; constructor(_cylinders:string) { this.cylinders = _cylinders; } }
在创建引擎的时候需要传入一个参数,这时候不需要修改Car类,只需要修改主程序即可。(原本我们需要先修改 Car 类,再修改主程序,现在只需要修改主程序)
主程序代码:
1 2 3 4
main(){ const car = new Car(new Engine('引擎启动机2'), new Tires1()); car.drive(); }
解决问题2:如果想在Car上使用不同品牌的轮胎,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13
export class Tires { public make = '品牌'; } export class Tire1 extends Tires { public make = '品牌1'; } export class Tire2 extends Tires { public make = '品牌2'; } export class Car { //。。。。。。其他代码省略。。。。。。。 constructor(public engine: Engine, public tires: Tires) {} }
此时不需要修改Car类,只需要修改主程序即可: 主程序代码:
1 2 3 4 5 6 7 8
main(){ // 使用品牌1的轮胎 const car1 = new Car(new Engine('引擎启动机1'), new Tires1()); car.drive(); // 使用品牌2的轮胎 const car2 = new Car(new Engine('引擎启动机2'), new Tires2()); car.drive(); }
main(){ // 创建一个共享服务中心Service const shareService = new Service(); const car1 = new Car(shareService); const car2 = new Car(shareService); // car1向服务中心存数据 car1.setDataToService('this data is from car1.'); // car2从服务中心取数据 car2.getDataFromService(); }