Skip to content

Instantly share code, notes, and snippets.

@arttuladhar
Last active May 8, 2019 16:52
Show Gist options
  • Save arttuladhar/4da5695837aed44cd8b6729c0687adce to your computer and use it in GitHub Desktop.
Save arttuladhar/4da5695837aed44cd8b6729c0687adce to your computer and use it in GitHub Desktop.
package com.art.designpatterns.strategy;
import com.google.common.collect.Lists;
import java.util.List;
public class StrategyDemo {
public static void main(String[] args) {
PromotionStrategy halfOffPromo = new HalfOffPromotionStrategy();
PromotionStrategy clearancePromo = new ClearancePromotionStrategy();
Customer customer1 = new Customer(halfOffPromo);
customer1.addItem(100.0);
customer1.addItem(50.0);
customer1.addItem(20.0);
System.out.println("Customer 1");
System.out.println("Total: " + customer1.getTotalBeforePromo());
System.out.println("Total (After Promo): " + customer1.getTotalAfterPromo());
Customer customer2 = new Customer(clearancePromo);
customer2.addItem(100.0);
customer2.addItem(50.0);
customer2.addItem(20.0);
System.out.println("Customer 2");
System.out.println("Total: " + customer2.getTotalBeforePromo());
System.out.println("Total (After Promo):" + customer2.getTotalAfterPromo());
}
}
class Customer {
private List<Double> items;
private PromotionStrategy promotionStrategy;
public Customer(PromotionStrategy promotionStrategy) {
this.promotionStrategy = promotionStrategy;
this.items = Lists.newArrayList();
}
public void addItem(Double item){
items.add(item);
}
public double getTotalBeforePromo(){
double total = items.stream().mapToDouble(i -> i).sum();
return total;
}
public double getTotalAfterPromo(){
double total = getTotalBeforePromo();
double promotion = promotionStrategy.getPromotion(total);
return total - promotion;
}
}
interface PromotionStrategy{
double getPromotion(Double totalAmount);
}
class HalfOffPromotionStrategy implements PromotionStrategy {
@Override
public double getPromotion(Double totalAmount) {
return totalAmount * 0.5;
}
}
class ClearancePromotionStrategy implements PromotionStrategy{
@Override
public double getPromotion(Double totalAmount) {
return totalAmount * 0.75;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment