mercredi 28 mars 2018

Unable to overwrite decorator pattern method

I'm learning Decorator pattern and I couldn't wrap my brain around the method overwriting.

I have a Phone.ts class that has phoneDescription and cost getter. The cost getter should be overwritten with the cost of the phone brand class that extends to it.

Phone.ts

export default class Phone {
  private description: string;

  constructor(description = 'Default description') {
    this.description = description;
  }

  get phoneDescription() {
    return this.description;
  }

  get price(): number | void {
    throw new Error('This method must be overwritten!');
  }
}

I have a model-specific class. In this example, Pixel.

Pixel.ts

import Phone from './Phone';

export default class Pixel extends Phone {
  get cost(): number {
    return 800;
  }
}

So far so good. I am able to instantiate the Pixel class. And I'm able to get the the cost from the object.

PhoneDecorator.ts

import Phone from './Phone';

export default class PhoneDecorator extends Phone {}

But phone screens are pretty fragile. We need a screen protector. So,

ScreenProtector.ts

import PhoneDecorator from './PhoneDecorator';

export default class ScreenProtector extends PhoneDecorator {
  phone: any;

  constructor(phone: any) {
    super();
    this.phone = phone
  }

  get cost(): number {
    return 50 + this.phone.price;
  }
}

This screen protector should add 50 to the current price of the phone supplied in the constructor.

But I'm getting the error This method must be overwritten!

index.ts

import ScreenProtector from './ScreenProtector';
import Pixel from './Pixel';

let pixel = new Pixel();

pixel = new ScreenProtector(pixel);

console.log(pixel.cost)

Aucun commentaire:

Enregistrer un commentaire