samedi 20 février 2016

Strategy design pattern -> property vs method

I found out that there are at least two ways to look at strategy problem in C#. First, let's look at the method approach:

class Test
{
    private Action strategy;
    void Strategy1()
    {
        Console.WriteLine("Strategy1");
    }

    void Strategy2()
    {
        Console.WriteLine("Strategy2");
    }

    void Strategy()
    {
        strategy();
    }

    public Test(bool strategy1)
    {
        if (strategy1)
            strategy = Strategy1;
        else
            strategy = Strategy2;
    }
}

But we can also do the same thing in this manner:

class Test
{
    void Strategy1()
    {
        Console.WriteLine("Strategy1");
    }

    void Strategy2()
    {
        Console.WriteLine("Strategy2");
    }

    private Action Strategy { get; }

    public Test(bool strategy1)
    {
        if (strategy1)
            Strategy = Strategy1;
        else
            Strategy = Strategy2;
    }
}

Despite the fact, that they are almost equivalent, I feel like first one is more natural to me. Action associated with class should be a method, not a property. But are there any drawbacks using any of these methods? Which one should I choose? The second is cool because writing a function which's job is just to invoke delegate feels redundant.

Aucun commentaire:

Enregistrer un commentaire