我有客户,每个客户都有生成参考号的方法,但是每个客户的参考号都不同。我在下面有一个实现,但我很好奇是否存在任何可伸缩性问题,这是什么设计模式,或者哪种设计模式最适合这种情况:
//All customers will implement this.
public interface ICustomer
{
}
//All customers will implement this.
public interface IReferenceNumber
{
string GenerateReferenceNumber();
}
public class CustomerOne : ICustomer, IReferenceNumber
{
public string GenerateReferenceNumber()
{
return "Reference Implemenation 1";
}
}
public class CustomerTwo : ICustomer, IReferenceNumber
{
public string GenerateReferenceNumber()
{
return "Reference Implemenation 2";
}
}
我可以这样称呼它:
Dictionary<string,ICustomer> customers = new Dictionary<string,ICustomer>();
customers.Add("CustomerOne",new CustomerOne());
customers.Add("CustomerTwo",new CustomerTwo());
CustomerOne customerOne = (CustomerOne)customers["CustomerOne"];
CustomerTwo customerTwo = (CustomerTwo)customers["CustomerTwo"];
Console.WriteLine(customerOne.GenerateReferenceNumber());
Console.WriteLine(customerTwo.GenerateReferenceNumber());
以下是一些更具体的问题:
- 我拥有 ICustomer 的唯一原因是我不必做类似的事情
Dictionary<string,object> customers = new Dictionary<string,object>()
,但现在我想知道这是否IReferenceNumber
是不必要的,GenerateReferenceNumber
应该移到ICustomer
另外,我讨厌不得不这样做CustomerOne customerOne = (CustomerOne)customers["CustomerOne"];
。有没有一种方法可以让客户回来并在其上调用方法而无需显式转换?
似乎基于评论,我应该有类似的东西:
public class Customer
{
public string GenerateReferenceNumber()
{
//Logic
return "Default reference number";
}
}
但是,如果每个客户都需要唯一的逻辑来生成参考号,我怎么能只保留一个客户对象并覆盖行为,除非我有多个GenerateReferenceNumber
方法,one huge if else statement
或者different concrete implementations of customers
可以使用默认参考号或他们自己的唯一逻辑来生成一个。