Utilisation du design pattern strategy
This commit is contained in:
parent
c5067ca768
commit
2294ce5351
5 changed files with 42 additions and 17 deletions
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
package org.example;
|
||||
|
||||
public interface FeeCalculationStrategy {
|
||||
public double calculateFee(TicketType ticketType);
|
||||
}
|
||||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,25 +1,9 @@
|
|||
package org.example;
|
||||
|
||||
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) {
|
||||
double fee = 0;
|
||||
|
||||
// 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;
|
||||
}
|
||||
double fee = visitor.calculateFee(ticketType);
|
||||
return fee;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,8 +2,18 @@ package org.example;
|
|||
|
||||
public class Visitor {
|
||||
public int age; // years counter
|
||||
private FeeCalculationStrategy feeCalculationStrategy;
|
||||
|
||||
public Visitor (int age) {
|
||||
if (age < 14) {
|
||||
feeCalculationStrategy = new FeeCalculationStartegyForChildren();
|
||||
} else {
|
||||
feeCalculationStrategy = new FeeCalculationStrategyForAdults();
|
||||
}
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public double calculateFee(TicketType ticketType) {
|
||||
return feeCalculationStrategy.calculateFee(ticketType);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue