Strategy

About

Basically the implementation of a contract (interface).

Use Factories to reuse code that is similar.

circle-exclamation

Example

Lets suppose that in a Ride Entity, when a ride ends we must calculate the ride fare based on the date and time of each position generated by the ride.

But we must use a different multipler depending on the date of the month and time of the day.

FareCalculator.ts
export default interface FareCalculator {
    calculate(distance: number): number;
}

export class NormalFareCalculator implements FareCalculator {
    calculate(distance: number): number {
        return distance * 2;
    }
}

export class OvernightFareCalculator implements FareCalculator {
    calculate(distance: number): number {
        return distance * 3;
    }
}

export class SpecialDayFareCalculator implements FareCalculator {
    calculate(distance: number): number {
        return distance * 1;
    }
}

export class FareCalculatorFactory {
    static create(date: Date) {
        if (date.getDate() === 1) return new SpecialDayFareCalculator();
        if (date.getHours() > 22 || date.getHours() < 6) return new OvernightCalculator();
        return new NormalFareCalculator();
    }
}
circle-exclamation

Last updated