在创建班级结构时,我正在努力遵守 Liskov 替换原则。我想在 Day 类中存储一组日历项目。需要有几种不同类型的 CalendarItems,例如:
AppointmentItem
NoteItem
RotaItem
它们都共享抽象基类 CalendarItem 中存在的一些通用功能:
public abstract class CalendarBaseItem
{
public string Description { get; private set; }
public List<string> Notes { get; private set; }
public TimeSpan StartTime { get; private set; }
public TimeSpan EndTime { get; private set; }
public int ID { get; private set; }
public DateTime date { get; private set; }
code omitted...
}
但是例如RotaItem有一些额外的功能:
public class RotaItem : CalendarBaseItem
{
public string RotaName { get; private set; }
private bool spansTwoDays;
public bool spanTwoDays()
{
return this.spansTwoDays;
}
}
其他类也添加了自己的逻辑等。
我为我的日课收集了一组 CalendarBaseItem:
List<CalendarBaseItem> calendarItems;
但是在回顾这一点时,我可以看到我违反了 LSP 原则,因为我必须检查并转换每个具体类型才能获得我希望每个子类的功能。
如果有人能建议如何避免这个问题,我将不胜感激。我应该使用组合方法并向每个最终类添加一个 CalendarItem 类,例如
public class RotaItem
{
private CalendarBaseItem baseItem;
public string RotaName { get; private set; }
private bool spansTwoDays;
public RotaItem(baseArgs,rotaArgs)
{
baseItem = new CalendarBaseItem(baseArgs);
}
public bool spanTwoDays()
{
return this.spansTwoDays;
}
}
这里唯一的问题是我需要为我的 Day 类中的每个 Concrete CalendarItem 单独收集一个集合吗?