Strategy
About
Basically the implementation of a contract (interface).
Use Factories to reuse code that is similar.
The Factory decides which version of the Object to instanciate.
The Object that uses the Factory don't know which version will be used.
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.
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();
}
}Since the Factory can contain Independent Business Rules, FareCalculator can be a Domain Service.
Last updated