lundi 2 septembre 2019

Design Pattern : How to model an unknown future composition?

Imagine an existing commission system that currently depends on a sales channel. A sale done with a website yields a 2% commission for the sales person, a sale with a mobile app 5%, ... I would model it like this :

public enum SalesChannel { Website, MobileApp, PhysicalShop, ThirdParty };

public interface IRelatedToSalesChannel
{
    SalesChannel SalesChannel { get; set; }
}

public class Commission 
{
    public int CommissionId { get; set; }
    public int Percentage { get; set; }

    public IRelatedToSalesChannel RelatedToSalesChannel { get; set; }
}

Any future, currently unknown, relation would be added as an interface. For example a relation with the sales volume

public class SalesAmount 
{ 
   public int SalesAmountId { get; set; }
   public int SalesAmountMin { get; set; }
   public int SalesAmountMax { get; set; }
 }  

public interface IRelatedToSalesAmount
{
    SalesAmount  SalesAmount { get; set; }
}

public class Commission 
{
    public int CommissionId { get; set; }
    public int Percentage { get; set; }

    public IRelatedToSalesChannel RelatedToSalesChannel { get; set; }
    public IRelatedToSalesAmount RelatedToSalesAmount { get; set; }
 }

This seems to me to be a really common situation. Nevertheless I think I currently make too many modifications to the code for each new relation. Is there a better approach ? I am starting to learn the Factory Design Pattern, but I am not sure I can apply it here.

My current ideas :

  1. I could add a list of classes to the 'commission' class constructor.
public class Commission
{
    public int CommissionId { get; set; }
    public int Percentage { get; set; }

    public Commission(IRelatedToSalesChannel,IRelatedToSalesAmount,...)
    {
        //.....
    }
}

  1. Or drop the composition idea and define a common interface being just an Id to be implemented by related classes.
public interface IRelatedToCommission
{
    Guid RelatedToCommissionId { get; set; }
}

public class SalesAmount : IRelatedToCommission
{ 
    public int SalesAmountId { get; set; }
    public int SalesAmountMin { get; set; }
    public int SalesAmountMax { get; set; }

    public Guid  RelatedToCommissionId { get; set; }
}

public class Commission 
{
    public int CommissionId { get; set; }
    public int Percentage { get; set; }

    public IRelatedToCommission RelatedToCommission { get; set; }
}

  1. Combine 1. and 2.
public class Commission
{
    public int CommissionId { get; set; }
    public int Percentage { get; set; }

    public Commission (IList<IRelatedToCommission>)
    {
        //.....
    }
}

Any guidance or hints would be greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire