为现有类创建接口?

时间:2014-08-07 12:06:37

标签: c# design-patterns

我使用Model在屏幕上绘制一些系列。您可以创建类似LineSeriesCurveSeries的系列,并将其添加到模型中:Model.Series.Add(myLineSeries);。该系列有一个属性Points,其中保存了所有点,您可以轻松添加一些:myLineSeries.Points.Add(...);Model获取从基类Series继承的所有序列。

但是当我将它添加到Model并希望稍后添加一些点时,我必须将其转换回来:

//Model.Series[0].Points does not exists. I have to cast them...

var lineSeries = (Model.Series[0] as LineSeries);

if(lineSeries != null)
    lineSeries.Points.Add(...);

var curveSeries = (Model.Series[0] as CurveSeries);
//Same code for CurveSeries

//Same code for other series types...

所以我必须一遍又一遍地做同样的代码。如果您可以访问源代码,您可以说:让我们创建一个“点接口”或基类,其中所有都具有属性点。该系列只需继承基类或接口。现在你可以说:

var Series = (Model.Series[0] as IPointSeries);

//Code only one time :)

但现在我无法访问Series和Model的源代码。我不能改变Model也不能改变系列基类的实现。

是否有一种常见的方法可以在不更改模型或系列的源代码的情况下执行此操作?就像为现有系列创建一个界面以同样的方式访问它们一样?

1 个答案:

答案 0 :(得分:2)

您可以编写一组包装类,这样至少您不必编写多次了解多个基础类型的所有代码。

例如:

public class PointSeries
{
    public List<Point> Points { get { return new List<Point>(); } }
}

public class CurveSeries
{
    public List<Point> Points { get { return new List<Point>(); } }
}

public interface ISeriesWrapper
{
    List<Point> Points { get; }
}

public class PointSeriesWrapper : ISeriesWrapper
{
    public PointSeriesWrapper(PointSeries series)
    {
        _Series = series;
    }

    private PointSeries _Series;

    public List<Point> Points { get { return _Series.Points; } }
}

public class CurveSeriesWrapper : ISeriesWrapper
{
    public CurveSeriesWrapper(CurveSeries series)
    {
        _Series = series;
    }

    private CurveSeries _Series;

    public List<Point> Points { get { return _Series.Points; } }
}

public static class SeriesWrapper
{
    public static ISeriesWrapper Create(object series)
    {
        var pointSeries = series as PointSeries;
        if (pointSeries != null)
            return new PointSeriesWrapper(pointSeries);

        var curveSeries = series as CurveSeries;
        if (curveSeries != null)
            return new CurveSeriesWrapper(curveSeries);

        throw new NotSupportedException();
    }
}

使用示例:

var pointSeries = SeriesWrapper.Create(Model.Series[0]);
lineSeries.Points.AddRange(pointSeries.Points);