Jul 10 2023
public decimal CalculateDiscount(Customer customer, decimal orderTotal)
{
if (customer.IsVIP)
{
return orderTotal * 0.8m; // 20% discount
}
else if (customer.IsRegular)
{
return orderTotal * 0.9m; // 10% discount
}
else if (customer.IsNew)
{
return orderTotal * 0.95m; // 5% discount
}
else
{
return orderTotal; // no discount
}
}
public abstract class DiscountHandler
{
protected DiscountHandler _nextHandler;
public void SetNextHandler(DiscountHandler nextHandler)
{
_nextHandler = nextHandler;
}
public abstract decimal CalculateDiscount(Customer customer, decimal orderTotal);
}
public class VIPDiscountHandler : DiscountHandler
{
public override decimal CalculateDiscount(Customer customer, decimal orderTotal)
{
if (customer.IsVIP)
{
return orderTotal * 0.8m; // 20% discount
}
return _nextHandler?.CalculateDiscount(customer, orderTotal) ?? orderTotal;
}
}
public class RegularDiscountHandler : DiscountHandler
{
public override decimal CalculateDiscount(Customer customer, decimal orderTotal)
{
if (customer.IsRegular)
{
return orderTotal * 0.9m; // 10% discount
}
return _nextHandler?.CalculateDiscount(customer, orderTotal) ?? orderTotal;
}
}
public class NewCustomerDiscountHandler : DiscountHandler
{
public override decimal CalculateDiscount(Customer customer, decimal orderTotal)
{
if (customer.IsNew)
{
return orderTotal * 0.95m; // 5% discount
}
return _nextHandler?.CalculateDiscount(customer, orderTotal) ?? orderTotal;
}
}
public class NoDiscountHandler : DiscountHandler
{
public override decimal CalculateDiscount(Customer customer, decimal orderTotal)
{
return orderTotal; // no discount
}
}
var vipHandler = new VIPDiscountHandler();
vipHandler.SetNextHandler(new RegularDiscountHandler())
.SetNextHandler(new NewCustomerDiscountHandler())
.SetNextHandler(new NoDiscountHandler());
decimal discountAmount = vipHandler.CalculateDiscount(customer, orderTotal);
Join 13,250+ subscribers to improve your .NET Knowledge.
Go-to resource for understanding the core concepts of design patterns without the overwhelming complexity. In this concise and affordable ebook, I've distilled the essence of design patterns into an easy-to-digest format. It is a Beginner level. Check out it here.
Every Monday morning, I share 1 actionable tip on C#, .NET & Arcitecture topic, that you can use right away.
Subscribe to the TheCodeMan.net and be among the 13,250+ subscribers gaining practical tips and resources to enhance your .NET expertise.