ILoyaltyDataService 只有两个方法:
public interface ILoyaltyDataService
{
void AddPoints(Guid customerId,int points);
void SubstractPoints(Guid customerId, int points);
}
ILoyaltyDataService 作为数据库接口,会通过DI的方式传入到业务层的构造函数。因为我们现在只集中在业务逻辑层,所以我们在数据服务层只是简单地打印一些东西就好了,FakeLoyaltyDataService 实现了ILoyaltyDataService 如下:
public class FakeLoyalDataService:ILoyaltyDataService
{
public void AddPoints(Guid customerId, int points)
{
Console.WriteLine("客户{0}增加了{1}积分",customerId,points);
}
public void SubstractPoints(Guid customerId, int points)
{
Console.WriteLine("客户{0}减少了{1}积分", customerId, points);
}
}
到这里,已经完成了累积积分的业务逻辑!现在回到客户关心的问题上,如何兑换积分?创建一个接口ILoyaltyRedemptionService :
public interface ILoyaltyRedemptionService
{
void Redeem(Invoice invoice, int numberOfDays);
}
/// <summary>
/// 发票实体
/// </summary>
public class Invoice
{
public Guid Id { get; set; }
public Customer Customer { get; set; }
public Vehicle Vehicle { get; set; }
public int CostPerDay { get; set; }
public decimal Discount { get; set; }
}
兑换积分是基于客户租赁的车型和兑换的天数从客户的账户中减去积分,并填充发票中的折扣金额。代码如下:
public class LoyalRedemptionService:ILoyaltyRedemptionService
{
private readonly ILoyaltyDataService _loyaltyDataService;
public LoyalRedemptionService(ILoyaltyDataService loyaltyDataService)
{
_loyaltyDataService = loyaltyDataService;
}
public void Redeem(Invoice invoice, int numberOfDays)
{
var pointsPerDay = 10;
if (invoice.Vehicle.Size>=Size.Luxury)
{
pointsPerDay = 15;
}
var totalPoints = pointsPerDay*numberOfDays;
invoice.Discount = numberOfDays*invoice.CostPerDay;
_loyaltyDataService.SubstractPoints(invoice.Customer.Id,totalPoints);
}
}
测试业务逻辑
下面创建一个控制台UI模拟业务逻辑的使用:
class Program
{
static void Main(string[] args)
{
SimulateAddingPoints();//模拟累积
Console.WriteLine("***************");
SimulateRemovingPoints();//模拟兑换
Console.Read();
}
/// <summary>
/// 模拟累积积分
/// </summary>
static void SimulateAddingPoints()
{
var dataService=new FakeLoyalDataService();//这里使用的数据库服务是伪造的
var service=new LoyaltyAccrualService(dataService);
var agreement=new RentalAgreement
{
Customer = new Customer
{
Id = Guid.NewGuid(),
Name = "tkb至简",
DateOfBirth = new DateTime(2000,1,1),
DriversLicense = "123456"
},
Vehicle = new Vehicle
{
Id = Guid.NewGuid(),
Make = "Ford",
Model = "金牛座",
Size = Size.Compact,
Vin = "浙-ABC123"
},
StartDate = DateTime.Now.AddDays(-3),
EndDate = DateTime.Now
};
service.Accrue(agreement);
}
/// <summary>
/// 模拟兑换积分
/// </summary>
static void SimulateRemovingPoints()
{
var dataService = new FakeLoyalDataService();
var service = new LoyalRedemptionService(dataService);
var invoice = new Invoice
{
Customer = new Customer
{
Id = Guid.NewGuid(),
Name = "Farb",
DateOfBirth = new DateTime(1999, 1, 1),
DriversLicense = "abcdef"
},
Vehicle = new Vehicle
{
Id = Guid.NewGuid(),
Make = "奥迪",
Model = "Q7",
Size = Size.Compact,
Vin = "浙-DEF123"
},
CostPerDay = 100m,
Id = Guid.NewGuid()
};
service.Redeem(invoice,3);//这里兑换3天
}
}
运行程序,伪造的数据服务会在控制台上打印一些东西,结果如下:
(编辑:成都站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|