We have a system which we use to charge the customers for different type of charges.
There are multiple charge types and each charge type includes different charge items.
The below is what I have come up with using the Factory Method, the problem with this one is that I need to be able to pass different parameters to each Calculate function depending on the charge type, how can I achieve this?
//product abstract class
public abstract class ChargeItem
{
public abstract List<ChargeResults> Calculate();
}
//Concrete product classes
public class ChargeType1 : ChargeItem
{
public override List<ChargeResults> Calculate()
{
return new List<ChargeResults> { new ChargeResults { CustomerId = 1, ChargeTotal = 10} };
}
}
public class ChargeType2 : ChargeItem
{
public override List<ChargeResults> Calculate()
{
return new List<ChargeResults> { new ChargeResults { CustomerId = 2, ChargeTotal = 20} };
}
}
public class ChargeType3 : ChargeItem
{
public override List<ChargeResults> Calculate()
{
return new List<ChargeResults> { new ChargeResults { CustomerId = 3, ChargeTotal = 30} };
}
}
//Creator abstract class
public abstract class GeneralCustomerCharge
{
//default constructor invokes the factory class
protected GeneralCustomerCharge()
{
this.CreateCharges();
}
public List<ChargeItem> ChargeItems { get; protected set; }
public abstract void CreateCharges();
}
public class AssetCharges : GeneralCustomerCharge
{
public override void CreateCharges()
{
ChargeItems = new List<ChargeItem> { new ChargeType1(), new ChargeType2() };
}
}
public class SubscriptionCharges : GeneralCustomerCharge
{
public override void CreateCharges()
{
ChargeItems = new List<ChargeItem> { new ChargeType3() };
}
}
public class ChargeResults
{
public int CustomerId { get; set; }
public decimal ChargeTotal { get; set; }
}
And the usage is:
var newAssetCharge = new AssetCharges();
foreach (ChargeItem chargeItem in newAssetCharge.ChargeItems)
{
foreach (var item in chargeItem.Calculate())
{
Console.WriteLine("Asset Charges For Customer Id: {0}, Charge Total: {1}", item.CustomerId, item.ChargeTotal);
}
}
I need to be able to pass different type of parameters to the chargeItem.Calculate() from within the foreach loop depending on the Calculate method I am calling, how can I achieve this?
I was planning to create different charge type parameter classes for each charge type, then determine the charge type and using some if else statements call the Calculate function passing the relevant parameter type but I don't think it is a good idea. Is there a better way of doing this, or is there are another completely different way of achieving what I am trying to do here?
Thanks
var newAssetCharge = new AssetCharges();
I have the parameters. – Thunellchargetype
hardcoded to a customer? – Fredricpublic abstract class ChargeItem { public abstract List<ChargeResults> Calculate<U>(U obj); }
– Babar