Reputation: 6894
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)
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.
Upvotes: 0
Views: 239
Reputation: 77348
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.
Upvotes: 3
Reputation: 31
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.
Upvotes: 1
Reputation: 46975
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.
Upvotes: 1