Search code examples
design-patternsencapsulationabstraction

Abstraction of behavioural logic - is there a design pattern?


I need to abstract some behavioural code and have a problem trying to reference the objects in the class that is calling these behaviours, let me try to explain:

My "parent" class, has a property called CurrentPage. I also have some behavioural logic, that modifies the CurrentPage property, currently this is written in the same class. I now need to reuse that behaviour in lots of places so I want to encapsulate/abstract that into a seperate ... erm... class??

I can sense that there is probably a design pattern that will meet my needs, but I can't figure out which one to use.

Can anyone out there help??

Thanks, Mark

(I am using C#, Silverlight and MVVM. CurrentPage is a notification property, not a field, so cannot be passed as a ref type into a Behaviour sub-class)

UPDATE: Example added as requested:

class MainApp
{
    public static string CurrentPage { get; set; }

    /// <summary>
    /// Entry point into console application.
    /// </summary>
    static void Main()
    {
        CurrentPage = "Default value";

        Console.WriteLine(CurrentPage);

        DoWork();

        Console.WriteLine(CurrentPage);

        Console.ReadLine();

    }


    private static void DoWork()
    {
        CurrentPage = "A new page";
    }

}

I'm trying to extract DoWork() into a seperate class.


Solution

  • Abstract the behavior into its own class. Then delegate to it. If you had to name it, I guess this is the "strategy" pattern.

    For example:

    class MainApp
    {
        ...
    
        void DoWork()
        {
            CurrentPage = "A new page";
        }
    }
    

    Might end up like:

    class PageModifier
    {
        void ModifyCurrentPage(MainApp instance)
        {
            instance.CurrentPage = "A new page";
        }
    }
    
    class MainApp
    {
        ...
        PageModifier _mod;
    
        void DoWork()
        {
            _mod.ModifyCurrentPage(this);
        }
    }
    

    Now you can use PageModifier all over the place and the behavior is kept in one location.