mercredi 27 avril 2016

using the factory pattern with derived classes accepting diverse number of parameters

I'm using the following factory pattern:

using System;

class Program
{
    abstract class Position
    {
    public abstract string Title { get; }
    }

    class Manager : Position
    {
    public override string Title
    {
        get
        {
        return "Manager";
        }
    }
    }

    class Clerk : Position
    {
    public override string Title
    {
        get
        {
        return "Clerk";
        }
    }
    }

    class Programmer : Position
    {
    public override string Title
    {
        get
        {
        return "Programmer";
        }
    }
    }

    static class Factory
    {
    /// <summary>
    /// Decides which class to instantiate.
    /// </summary>
    public static Position Get(int id)
    {
        switch (id)
        {
        case 0:
            return new Manager();
        case 1:
        case 2:
            return new Clerk();
        case 3:
        default:
            return new Programmer();
        }
    }

The way to use this pattern is in the example from the same source:

static void Main()
{
for (int i = 0; i <= 3; i++)
{
    var position = Factory.Get(i);
    Console.WriteLine("Where id = {0}, position = {1} ", i, position.Title);
}
}

Should I be using this pattern if my derived classes are using different numbers of parameters for their constructors?

The probable modification that I would need to make is when instantiating the factory:

var position = Factory.Get(i);

I would probably need to pass in parameters for all of the derived classes, regardless of whether they would use them or not:

var position = Factory.Get(i, param1, param2, param3);

and the switch statement would need to be modified:

public static Position Get(int id, param1, param2, param3) //HERE IS THE MODIFIED PARAM LIST
{
    switch (id)
    {
    case 0:
        return new Manager(param1); //MODIFIED
    case 1:
    case 2:
        return new Clerk(param2, param3); //MODIFIED
    case 3:
    default:
        return new Programmer(param3); //MODIFIED
    }
}

Do the modifications that I've made to the factory pattern break the pattern, and should I be using a different pattern for object creation?

Aucun commentaire:

Enregistrer un commentaire