Search code examples
typescriptclassoopstructure

How to implement a wrapper class for multiple classes in Typescript


I have multiple APIs for providing same functionality, I want to wrap them so i have to only handle one class and more APIs can be added in the future.

What i have done yet:

class FirstAPI: API {}

class SecondAPI: API {}

class GeneralAPI: API {
  public api: API;

  constructor(type: string){
    if(type === 'first') {
      this.api = new FirstAPI();
    }
    if(type === 'second') {
      this.api = new SecondAPI();
    }
  }


  someMethod(){
    this.api.someMethod();
  }

}

As you can see doing this i have to repeat my methods unnecessarily and i have to manually handle input and output type in the General class as well.

Please suggest some, better/elegant solution with proper type support.


Solution

  • The problem with your current code is the use of if...else which violates the OCP(Open-close principle).

    What you really need here is a factory pattern, which you will register all the available APIs that can be created. After which, you may just use the key to create them accordingly.

    for example (just for idea)

    ApiFactory.register('firstApi', FirstAPI);
    ApiFactory.register('secondApi' SecondAPI);
    const api: API = ApiFactory.get('firstApi');
    api.someMethod();
    

    factory-pattern explained

    more explanation on factory-pattern