mercredi 15 avril 2020

Choosing between TypeScript Adapter / Facade / Proxy etc. patterns

I have trouble choosing the right pattern for implementation. The main idea is using one instance of class calling the same methods to achieve the same results. Should I use Adapter / Facade / Proxy or something else? Should I replace extends with implements? Is there a common or recommended pattern for this in TypeScript?

Abstract class:

abstract class InformerBasic {
  abstract getImageDimensions(path: string): null | { height: number; width: number };
  public whatWeHave(path: string): null | { height: number; width: number } {
    return this.getImageDimensions(path);
  }
}

Extended classes

class InformerLocalFileSystem extends InformerBasic {
  public getImageDimensions(path: string): null | { height: number; width: number } {
    return { height: 200, width: 200 }; // Actual unique code must be here
  }
}

class InformerCloudDropBox extends InformerBasic {
  public getImageDimensions(path: string): null | { height: number; width: number } {
    return { height: 200, width: 200 }; // Actual unique code must be here
  }
}

Usable class

class Informer extends InformerBasic {
  protected implementation;
  public constructor(instance: InformerBasic) {
    super();
    this.implementation = instance;
  }
  public getImageDimensions(path: string): null | { height: number; width: number } {
    return this.implementation.getImageDimensions(path);
  }
}

Usage

const instanceOfLocal = new InformerLocalFileSystem();
const informerLocal = new Informer(instanceOfLocal);
console.log(informerLocal.whatWeHave("/path/to/image"));

const instanceOfDropBox = new InformerCloudDropBox();
const informerDropBox = new Informer(instanceOfDropBox);
console.log(informerDropBox.whatWeHave("/path/to/image"));

Aucun commentaire:

Enregistrer un commentaire