Nov 25 2024
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);
1. Design Patterns that Deliver
This isn’t just another design patterns book. Dive into real-world examples and practical solutions to real problems in real applications.Check out it here.
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.
Join 14,250+ subscribers to improve your .NET Knowledge.
Subscribe to the TheCodeMan.net and be among the 14,250+ subscribers gaining practical tips and resources to enhance your .NET expertise.