public interface IRecord
{
}
public class BirthRecord : IRecord
{
public string CityOfBirth;
public Date DateOfBirth;
public BirthRecord(string cityOfBirth, Date dateOfBirth)
{
// assign these to properties
}
}
public class CarRecord : IRecord
{
public Color Color;
public string Manufacturer;
public CarRecord(Color color, string manufacturer)
{
// assign these to properties
}
}
public interface IAccount
{
public List<IRecord> Records { get; set; }
}
public class Client
{
public void ProcessAccount(IAccount account)
{
foreach(IRecord record in account.Records)
{
if(record is CarRecord)
handleCarRecord((CarRecord)record);
else if(record is BirthRecord)
handleBirthRecord((BirthRecord)record);
}
}
}
因此,当您到达客户端并想要处理值对象时,您必须进行各种杂乱的类型检查和强制转换——这是一种可接受的模式还是我犯了一个更根本的设计错误?如果不是其他 OOD 原则,这似乎违反了 OCP。有没有其他选择?