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开发者_StackOverflow社区-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.
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.
Don't know c# but this sounds like it may be appropriate for an interface definition. However usually this means leaving out the actual implementation of the behaviors you wish to define.
Move the logic in its separate class, expose its relevant methods and call them whenever needed from your initial class. Typical, the service methods will take like argument an instance of your intial class. Although I do not feel it is directly about design patterns here, more about design principles, have a look at the GoF book; it will worth it.
精彩评论