避免反箭头模式

时间:2015-09-23 12:13:00

标签: c# oop solid-principles

我有模板模板方法,可以为不同类型的图表实现基本功能。每种图表类型FastChartSlowChart都会实现缩放功能Zoom()此功能应对不同的系列AreaSeriesCandleStickSeries进行不同的缩放。

我认为

    public override void Zoom()
    {
        if (BTF.AreaSeries != null)
        {

        }
        if (BTF.CandleStickSeries!=null)
        { 

        }
    }

非常糟糕的主意因为如果我应该有10种类型的系列,我应该在每个函数中生成10 if语句。怎么避免这个?

namespace ConsoleApplication38765
{
public interface IFirstType
{
    AreaSeries AreaSeries { get; set; }
    CandleStickSeries CandleStickSeries { get; set; }
}
public class BoxTypeFirst : IFirstType
{
    public AreaSeries AreaSeries { get; set; }
    public CandleStickSeries CandleStickSeries { get; set; }
}
public interface IChart
{
    void Zoom();
    void DrawChart();
    void GetPoints();
}
public interface IRectangle
{
    void AddRectangles();
}
public abstract class BaseChart:IChart
{
    public abstract void Zoom();

    public virtual void DrawChart()
    {
    }

    public  virtual void GetPoints()
    {
    }
}
public class FastChart:BaseChart
{
    BoxTypeFirst BTF = new BoxTypeFirst();
    public override void Zoom()
    {
        if (BTF.AreaSeries != null)
        {

        }
    }
}
public class SlowChart:BaseChart,IRectangle
{
    BoxTypeFirst BTF = new BoxTypeFirst();

    public override void Zoom()
    {
        if (BTF.CandleStickSeries != null)
        {

        }
    }
    public void AddRectangles()
    {

    }
}
class Program
{
    static void Main(string[] args)
    {
        BaseChart BS = new SlowChart();
        BS.Zoom();
        BS = new FastChart();
        BS.Zoom();
    }
}
}

1 个答案:

答案 0 :(得分:0)

作为一个选项,您可以让BaseChart使用它所使用的系列,并在那里检查null。

public abstract class BaseChart
{
    public void Zoom()
    {
        if (Series != null)
        {
            OnZoom();
        }
    }

    protected abstract void OnZoom();

    public virtual void DrawChart()
    {
    }

    protected abstract object Series { get; }

    public virtual void GetPoints()
    {
    }
}

public class FastChart : BaseChart
{
    private readonly BoxTypeFirst BTF = new BoxTypeFirst();

    protected override void OnZoom()
    {
        throw new System.NotImplementedException();
    }

    protected override object Series
    {
        get { return BTF.AreaSeries; }
    }
}

public class SlowChart : BaseChart
{
    private readonly BoxTypeFirst BTF = new BoxTypeFirst();

    protected override void OnZoom()
    {
        throw new System.NotImplementedException();
    }

    protected override object Series
    {
        get { return BTF.CandleStickSeries; }
    }
}

但无论如何你的代码设计都有气味。我看不到全貌,所以我不能说太多。