Created
September 25, 2019 00:59
-
-
Save LudgerPeters/b444d9e06d1c166055fba1c7318a2320 to your computer and use it in GitHub Desktop.
StratergyPattern.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.ArrayList; | |
| interface BillingStrategy { | |
| // Use a price in cents to avoid floating point round-off error | |
| int getActPrice(int rawPrice); | |
| } | |
| class NormalBillingStratergy implements BillingStrategy{ | |
| @Override | |
| public int getActPrice(int rawPrice) { | |
| return rawPrice; | |
| } | |
| } | |
| class HappyHourStrategy implements BillingStrategy{ | |
| @Override | |
| public int getActPrice(int rawPrice) { | |
| return rawPrice / 2; | |
| } | |
| } | |
| class Customer { | |
| private final ArrayList<Integer> drinks = new ArrayList<>(); | |
| private BillingStrategy strategy; | |
| public Customer(BillingStrategy strategy) { | |
| this.strategy = strategy; | |
| } | |
| public void add(int price, int quantity) { | |
| this.drinks.add(this.strategy.getActPrice(price*quantity)); | |
| } | |
| // Payment of bill | |
| public void printBill() { | |
| int sum = this.drinks.stream().mapToInt(v -> v).sum(); | |
| System.out.println("Total due: " + sum / 100.0); | |
| this.drinks.clear(); | |
| } | |
| // Set Strategy | |
| public void setStrategy(BillingStrategy strategy) { | |
| this.strategy = strategy; | |
| } | |
| } | |
| public class StrategyPattern { | |
| public static void main(String[] arguments) { | |
| // Prepare strategies | |
| BillingStrategy normalStrategy = new NormalBillingStratergy(); | |
| BillingStrategy happyHourStrategy = new HappyHourStrategy(); | |
| Customer firstCustomer = new Customer(normalStrategy); | |
| // Normal billing | |
| firstCustomer.add(100, 1); | |
| // Start Happy Hour | |
| firstCustomer.setStrategy(happyHourStrategy); | |
| firstCustomer.add(100, 2); | |
| // New Customer | |
| Customer secondCustomer = new Customer(happyHourStrategy); | |
| secondCustomer.add(80, 1); | |
| // The Customer pays | |
| firstCustomer.printBill(); | |
| // End Happy Hour | |
| secondCustomer.setStrategy(normalStrategy); | |
| secondCustomer.add(130, 2); | |
| secondCustomer.add(250, 1); | |
| secondCustomer.printBill(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment