-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDiscountCalculator.cs
117 lines (99 loc) · 2.99 KB
/
DiscountCalculator.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
using System;
using System.Collections.Generic;
namespace rule.pattern
{
public interface IDiscountRule
{
decimal CalculateCustomerDiscount(Customer customer);
}
public class BirthdayDiscountRule : IDiscountRule
{
public decimal CalculateCustomerDiscount(Customer customer)
{
if (customer.DateOfBirth.Month == DateTime.Today.Month &&
customer.DateOfBirth.Day == DateTime.Today.Day)
{
return 0.10m;
}
return 0m;
}
}
public class SeniorDiscountRule : IDiscountRule
{
public decimal CalculateCustomerDiscount(Customer customer)
{
if (customer.DateOfBirth < DateTime.Now.AddYears(-65))
{
return .05m;
}
return 0m;
}
}
public class VeteranRule : IDiscountRule
{
public decimal CalculateCustomerDiscount(Customer customer)
{
if (customer.IsVeteran)
{
return .10m;
}
return 0m;
}
}
public class LoyalCustomerRule : IDiscountRule
{
public int _yearsAsCustomer { get; }
public decimal _discount { get; }
public LoyalCustomerRule(int yearsAsCustomer, decimal discount)
{
_yearsAsCustomer = yearsAsCustomer;
_discount = discount;
}
public decimal CalculateCustomerDiscount(Customer customer)
{
if (customer.DateOfFistPurchase.HasValue)
{
if (customer.DateOfFistPurchase.Value.AddYears(_yearsAsCustomer) <= DateTime.Today)
{
var birthdayRule = new BirthdayDiscountRule();
return _discount + birthdayRule.CalculateCustomerDiscount(customer);
}
}
return 0m;
}
}
public class FirstTimeRule : IDiscountRule
{
public decimal CalculateCustomerDiscount(Customer customer)
{
if (!customer.DateOfFistPurchase.HasValue)
{
return .15m;
}
return 0m;
}
}
public class DiscountCalculator
{
List<IDiscountRule> _rules = new List<IDiscountRule>();
public DiscountCalculator()
{
_rules.Add(new BirthdayDiscountRule());
_rules.Add(new SeniorDiscountRule());
_rules.Add(new VeteranRule());
_rules.Add(new LoyalCustomerRule(1, 0.10m));
_rules.Add(new LoyalCustomerRule(5, 0.12m));
_rules.Add(new LoyalCustomerRule(10, 0.20m));
_rules.Add(new FirstTimeRule());
}
public decimal CalculateDiscountPercentage(Customer customer)
{
decimal discount = 0;
foreach (var rule in _rules)
{
discount = Math.Max(rule.CalculateCustomerDiscount(customer), discount);
}
return discount;
}
}
}