【发布时间】:2015-05-19 16:07:34
【问题描述】:
不要重复自己 或者 封装?
假设我创建了以下内容:
- 实现 IList 的接口 IMask。
- 实现 IMask 的 Class Spot。
- 一个包含几个整数和一个 Spot 作为字段的类标记。
我想让 Marker 实现 IMask 接口。但后来我会重复自己(最后检查代码) 或者我可以在 Marker 公众中成为我的 Spot。但随后我将公开我的课程的实现。 或者我可以从 Spot 继承我的 Spot,但这不是理想的解决方案,因为从语义上讲,标记不是 Spot 的特定类型。
如果我创建另一个具有 Spot 作为字段的类,并且我想再次实现 IMask 接口,该怎么办? 我会再次重复自己。 那么,我应该如何进行呢?我应该公开 Spot 中的列表吗?然后将标记中的 Spot 公开? 还是我应该重复通话?
interface IMask : IList<Point>
{
public void MoveTo(Point newCenter);
// ... other Methods
}
public class Spot : IMask
{
List<Point> points;
public void DoSpotyStuff()
{
// blabla
}
// Other methods
// ...
// Finally the implementation of IMask
public void MoveTo(Point newCenter)
{
// blabla
}
// And of course the IList methods
public void Add(Point newPoint)
{
points.Add(newPoint);
}
}
public class Marker : IMask
{
private Spot mySpot;
private int blargh;
// Other fields
public void MarkeryMethod()
{
// Blabla
}
// HERE IS THE PROBLEM: Should I do this and repeat myself
public void MoveTo(Point newCenter) { mySpot.MoveTo(newCenter); }
// And here I'm REALLY starting to repeat myself
public void Add(Point newPoint) { mySpot.Add(newPoint); }
}
观察: 接口 IMask 不是从 List 继承的。它正在实现 IList 接口,而后者又是implements ICollection, IEnumerable 假设 Marker 在语义上不是特殊的 Spot。因此,即使我可以从 Spot 继承并解决问题,它也不是最好的解决方案。
【问题讨论】:
-
我没有从 IList 继承。 IList 是一个接口,我的意思是:每当一个类实现 IMask 时,它也实现了 IList。
-
为什么你的
Marker不继承自Spot,因为听起来你的标记是一个专门的位置 -
James,在链接的问题中,用户从 List 继承,这是一个实现 IList 接口的类。我不这样做。我的接口只是在实现另一个接口。
-
IMask只是带有MoveTo方法的List<Point>吗?如果是这样,为什么不将MoveTo设为扩展方法?
标签: c# inheritance interface