如何使用初始化时不可用的数据初始化类?

时间:2020-06-06 13:25:48

标签: typescript design-patterns

我必须为此控制器类编写测试。控制器类的validate函数将被直接调用或作为入口点。该控制器使用SomeService类的doSomethingWithData。 SomeService类需要的数据在构造Controller时不可用,但作为validate函数的参数。

// someservice.ts
class SomeService {
    data: string;

    constructor(data: string) {
        this.data = data;
    }

    doSomethingWithData() {
        // Code to Do something here.
    }
}

// Controller.ts
import SomeService from './someservice.ts';

class MyController {
      validate(event: string) {
           let service = new SomeServce(event);
           service.doSomethingWithData();
      }

}

要测试它,我想使用模拟服务,因此我将控制器重写为:

// Controller.ts
import SomeService from './someservice.ts';

class MyController {
      myservice: SomeService = new SomeService(/* Problem: What should I write here, this data would come in future as validate's argument /*);
      validate(event: string) {
           let service = new SomeServce(event);
           service.doSomethingWithData();
      }

}

为克服这个问题,我重新编写了服务的构造函数和控制器用法

 // someservice.ts
class SomeService {
    data: string = '';

    initiateService(data: string) {
        this.data = data;
    }
    doSomethingWithData() {
        // Code to Do something here.
    }
}

// controller.ts
import SomeService from './someservice.ts';

class MyController {
      myservice: SomeService = new SomeService();
      validate(event: string) {
           service.initiate(event);
           service.doSomethingWithData();
      }

}

还有其他方法可以将数据传递给作为函数参数的服务吗?就像在这种情况下。我的临时解决方案是否足够好?有没有针对这种情况的设计模式?

1 个答案:

答案 0 :(得分:0)

可能的解决方案是使用“工厂”方法创建SomeService。这样,您可以在想要创建SomeService的其他版本时随时替换出工厂方法。

interface SomeService {
    doSomethingWithData: () => void;
}

class MyController {
    constructor(
        public serviceFactory: (event: string) => SomeService
    ) { }

    validate(event: string) {
        const service = this.serviceFactory(event);
        service.doSomethingWithData();
    }
}

Playground Link

相关问题