lundi 11 mars 2019

Correct implementation of factory

I'm trying to implement the factory pattern the correct way but I'm not sure if this is correct. I have three model classes derived from a base class like so:

class BaseStyle
{
    public string Name
    {
        get;
        set;
    }
}

class PointStyle : BaseStyle
{
    public PointStyle(string name)
    {
         Name = name;
    }
}

class LineStyle : BaseStyle
{
    public LineStyle(string name)
    {
         Name = name;
    }
}

class PolyStyle : BaseStyle
{
    public PolyStyle(string name)
    {
         Name = name;
    }
}

I then have a class called StyleFactory. This class takes a string to determine which type of Style to create and returns that Style.

public class StyleFactory
{
    public static ParentStyleModel CreateStyle(string styleType)
    {
        if (styleType == "point")
        {
            return CreatePointStyle();
        }
        if (styleType == "line")
        {
            return CreateLineStyle();
        }
        if (styleType == "poly")
        {
            return CreatePolytStyle();
        }
    }

    private static PointStyle CreatePointStyle()
    {
        //creates a pointstyle
    }

    private static LineStyle CreateLineStyle()
    {
        //creates a linestyle
    }

    private static PolyStyle CreatePolyStyle()
    {
        //creates a polystyle
    }
}

And then it's called in code like this:

PointStyle pointStyle = StyleFactory.CreateStyle("point");

Is this the best way to go about it? Should I split the three "Create" functions into their own separate class? Would using generics make more sense?

Aucun commentaire:

Enregistrer un commentaire