dimanche 28 octobre 2018

Design Pattern using generics

I have a series of interfaces that represent geometry entities. I want to extend these by providing some extra functionality called Stretch.

I want a method to pass a Curve and a Boundary and then get the resulted curve stretched to that boundary or nothing.

I have developed a mechanism like this to make it a general operation.

StretchOperations gets a Curve and a list of Stretchers. Then when we run the Stretch method on this class, it goes through its list of Stretchers and tries to stretch this Curve to the given Boundary.

I have came up with this pattern myself and it seems a bit odd to me! I was wondering if there is a similar design pattern, how can I improve this design.

I do not want to change the interface of my geometry objects though.

public class StretchOperations
{
    private IList<IStretcher<object, object>> m_stretchers { get; } =
        new List<IStretcher<object, object>>();

    private readonly ICurve3D m_curve;


    public void Add<TCurve, TBoundary>(IStretcher<TCurve, TBoundary> stretcher)
    {
        m_stretchers.Add(stretcher as IStretcher<object, object>);
    }


    public Operations(ICurve3D curve)
    {
        m_curve = curve;
    }


    public TCurve Stretch<TCurve, TBoundary>(TBoundary boundary) where TCurve: class 
    {
        foreach (var stretcher in m_stretchers)
        {

            var res = stretcher.Stretch(m_curve, boundary);
            if (res != null)
                return (TCurve) res;
        }

        return null;
    }
}

public interface IStretcher<TCurve, in TBoundary>
{
    TCurve Stretch(TCurve curve, TBoundary boundary);
}

public class ArcStretcher : IStretcher<IArc3D, ILine3D>
{
    public IArc3D Stretch(IArc3D curve, ILine3D boundary)
    {
        // Extends the arc till it reaches the boundary.
        return null;
    }
}

Aucun commentaire:

Enregistrer un commentaire