Utilisation du design pattern strategy

This commit is contained in:
Feror 2025-01-23 12:13:56 +01:00
parent c5067ca768
commit 2294ce5351
5 changed files with 42 additions and 17 deletions

View file

@ -0,0 +1,13 @@
package org.example;
public class FeeCalculationStartegyForChildren implements FeeCalculationStrategy {
private static final double CHILD_PRICE_BASE = 100;
public double calculateFee(TicketType ticketType) {
if (TicketType.HALF_DAY == ticketType) {
return CHILD_PRICE_BASE * 0.2;
} else if (TicketType.FULL_DAY == ticketType) {
return CHILD_PRICE_BASE * 0.5;
}
return 0;
}
}

View file

@ -0,0 +1,5 @@
package org.example;
public interface FeeCalculationStrategy {
public double calculateFee(TicketType ticketType);
}

View file

@ -0,0 +1,13 @@
package org.example;
public class FeeCalculationStrategyForAdults implements FeeCalculationStrategy {
private static final double ADULT_PRICE_BASE = 100;
public double calculateFee(TicketType ticketType) {
if (TicketType.HALF_DAY == ticketType) {
return ADULT_PRICE_BASE * 0.6;
} else if (TicketType.FULL_DAY == ticketType) {
return ADULT_PRICE_BASE * 1.2;
}
return 0;
}
}

View file

@ -1,25 +1,9 @@
package org.example; package org.example;
public class FeeCalculator { public class FeeCalculator {
private static final double CHILD_PRICE_BASE = 100;
private static final double ADULT_PRICE_BASE = 100;
public static double calculateFee(Visitor visitor, TicketType ticketType) { public static double calculateFee(Visitor visitor, TicketType ticketType) {
double fee = 0; double fee = visitor.calculateFee(ticketType);
// calculate price for adults
if ((visitor.age > 14) && (TicketType.HALF_DAY == ticketType)) {
fee = ADULT_PRICE_BASE * 0.6;
} else if ((visitor.age > 14) && (TicketType.FULL_DAY == ticketType)) {
fee = ADULT_PRICE_BASE * 1.2;
}
// calculate price for children
if ((visitor.age <= 14) && (TicketType.HALF_DAY == ticketType)) {
fee = CHILD_PRICE_BASE * 0.2;
} else if ((visitor.age <= 14) && (TicketType.FULL_DAY == ticketType)) {
fee = CHILD_PRICE_BASE * 0.5;
}
return fee; return fee;
} }
} }

View file

@ -2,8 +2,18 @@ package org.example;
public class Visitor { public class Visitor {
public int age; // years counter public int age; // years counter
private FeeCalculationStrategy feeCalculationStrategy;
public Visitor (int age) { public Visitor (int age) {
if (age < 14) {
feeCalculationStrategy = new FeeCalculationStartegyForChildren();
} else {
feeCalculationStrategy = new FeeCalculationStrategyForAdults();
}
this.age = age; this.age = age;
} }
public double calculateFee(TicketType ticketType) {
return feeCalculationStrategy.calculateFee(ticketType);
}
} }