何时增长接口,限制它,或使用实现来实现

本文关键字:实现 接口 何时增 | 更新日期: 2023-09-27 18:11:56

我经常在决定何时扩大或缩小接口或使用某些实现时遇到问题。考虑一个矩阵;它可以是正方形的,也可以不是,所以我写入:

interface IMatrix<T>
{
  void InsertColumn(int position);
  void InsertRow(int position);
  void DeleteColumn(int position);
  void DeleteRow(int position);
  T ValueAt(int row, int col); //gets the value
  void ValueAt(int row, int col, T value); //sets the value
}

所以,上面的矩阵可以是平方的,但它不一定是平方的。我的第一个想法是使用一个类来创建方阵的概念

class SquareMatrix<T> : IMatrix<T>
{
   private IMatrix<T> matrix;
   public SquareMatrix(IMatrix<T> matrix) {this.matrix = matrix;}
   public void InsertColumn(int position)
   {
     // Must ensure that a row and column are both added to keep it square
     this.matrix.InsertRow(position);
     this.matrix.InsertColumn(position);
   }
   // rest of methods similarly perform a row and column operation to keep square...
 }
}

然而,我很快意识到,我可以传递一个方阵到构造函数,得到一些糟糕的结果,因为现在我将做许多额外的操作。所以我觉得这不是一个很好的方法来限制接口只能是方形的,除非有更好的方法来实现这个类。

所以我想,嗯……方阵比正则矩阵更具限制性,也许我应该从中提取一个接口作为…

interface ISquareMatrix<T>
{
  void InsertRow(int position);// adds a row and column, name selected for inheritance purposes
  void DeleteRow(int position);// deletes a row and column, ...
  void ValueAt(int row, int col, T value);
  T ValueAt(int row, int col);
}
interface IMatrix<T> : ISquareMatrix<T>
{
  void InsertColumn(int position);// adds only a column and now InsertRow should not also insert a column
  void DeleteColumn(int position);// deletes only a column
}

这看起来不错,但有点打破了我关于继承的思路,因为SquareMatrix是IS-A矩阵,反之亦然。而且,由于我选择名字的方式使继承看起来很好,因此我对这种方法很谨慎。

abstract class MatrixBase<T> : IMatrix<T>
{
  //Base class simply provides a matrix that we can use
  IList<IList<T>> matrix = new List<IList<T>>();
  public MatrixBase(int rows, int columns)
  {
    if(rows < 1) {/*throw ...*/}
    if(columns < 1) {/*throw...*/}
    // add rows and columns
  }
  public abstract void InsertColumn(int position);
  // more abstract methods to implement interface
}
class Matrix<T> : MatrixBase<T>
{
  //override all methods so that insert column only inserts a column
  //and insert row only inserts a row
}
class SquareMatrix<T> : MatrixBase<T>//seems fishy since matrix base is an IMatrix
{
  //override all methods so that insert row inserts a row and column
  //and insert column calls insert row
}

所以你可以看到,方阵又回到了矩阵,尽管接口读起来是相反的。

不管怎样,这些都是我的想法;你如何建立方阵和不一定是方阵之间的关系?:)谢谢!

何时增长接口,限制它,或使用实现来实现

一般来说,接口应该只包含所有实现都可以合理地实现的方法。在这种情况下,我认为AddRowAddColumn方法不应该是接口的一部分,而应该是Matrix上的方法。

在。net框架中,有一些接口的例子过于宽泛,并且具有CanXxx属性,因此您可以在调用它之前检查方法是否对特定对象有意义。所以你也可以这样做,但我自己不太喜欢。