Guest User

Untitled

a guest
Jul 17th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. package com.art.designpatterns.strategy;
  2.  
  3. import com.google.common.collect.Lists;
  4. import java.util.List;
  5.  
  6. public class StrategyDemo {
  7.  
  8. /**
  9. *
  10. * Output
  11. *
  12. * Customer 1
  13. * Total: 170.0
  14. * Total (After Promo): 85.0
  15. * Customer 2
  16. * Total: 170.0
  17. * Total (After Promo):42.5
  18. *
  19. */
  20. public static void main(String[] args) {
  21. PromotionStrategy halfOffPromo = new HalfOffPromotionStrategy();
  22. PromotionStrategy clearancePromo = new ClearancePromotionStrategy();
  23.  
  24. Customer customer1 = new Customer(halfOffPromo);
  25. customer1.addItem(100.0);
  26. customer1.addItem(50.0);
  27. customer1.addItem(20.0);
  28.  
  29. System.out.println("Customer 1");
  30. System.out.println("Total: " + customer1.getTotalBeforePromo());
  31. System.out.println("Total (After Promo): " + customer1.getTotalAfterPromo());
  32.  
  33. Customer customer2 = new Customer(clearancePromo);
  34. customer2.addItem(100.0);
  35. customer2.addItem(50.0);
  36. customer2.addItem(20.0);
  37.  
  38. System.out.println("Customer 2");
  39. System.out.println("Total: " + customer2.getTotalBeforePromo());
  40. System.out.println("Total (After Promo):" + customer2.getTotalAfterPromo());
  41. }
  42. }
  43.  
  44. class Customer {
  45. private List<Double> items;
  46. private PromotionStrategy promotionStrategy;
  47.  
  48. public Customer(PromotionStrategy promotionStrategy) {
  49. this.promotionStrategy = promotionStrategy;
  50. this.items = Lists.newArrayList();
  51. }
  52.  
  53. public void addItem(Double item){
  54. items.add(item);
  55. }
  56.  
  57. public double getTotalBeforePromo(){
  58. double total = items.stream().mapToDouble(i -> i).sum();
  59. return total;
  60. }
  61.  
  62. public double getTotalAfterPromo(){
  63. double total = getTotalBeforePromo();
  64. double promotion = promotionStrategy.getPromotion(total);
  65. return total - promotion;
  66. }
  67. }
  68.  
  69. interface PromotionStrategy{
  70. double getPromotion(Double totalAmount);
  71. }
  72.  
  73. class HalfOffPromotionStrategy implements PromotionStrategy {
  74. @Override
  75. public double getPromotion(Double totalAmount) {
  76. return totalAmount * 0.5;
  77. }
  78. }
  79.  
  80. class ClearancePromotionStrategy implements PromotionStrategy{
  81. @Override
  82. public double getPromotion(Double totalAmount) {
  83. return totalAmount * 0.75;
  84. }
  85. }
Add Comment
Please, Sign In to add comment