Wednesday, June 09, 2010

 

DataObject method accessible with instance and without

Below explains how to create a single chunk of method logic in a class that is accessible from both an instance of that class and without any instance of the class.

1. Create some data object class, perhaps called Theme.

2. Create method to copy from Model into both instance and static
private static Theme toStatic(Model.Theme fromModel)
{
Theme theme = new Theme();
theme.ID = fromModel.ID;
return theme
}

private Theme toInstance(Model.Theme fromModel)
{
this.ID = fromModel.ID;
return null;
}
3. Create methods to preform the function both in an instance and without/statically.
public static Theme Get(int id)
{
return toStatic(WebService.GetTheme(id));
}
public Theme(int id)
{
toInstance(WebService.GetTheme(id));
}
4. create delegate to call ToStatic or ToInstance
private delegate Theme staticOrInstance(Model.Theme theme);
5. create method to preform the get action once
private static Theme Get(staticOrInstance statOrInst, int id)
{ return statOrInst(WebService.GetTheme(id)); }
6. change methods above to use delegate to send to single Get
public static Theme Get(int id)
{
return Get(toStatic, id);
}
public Theme(int id)
{
Get(toInstance, id);
}
7. This allows the dataobject to be used as.
string name = Theme.Get(4).Name;
//or
Theme newTheme = new Theme(4);
to use the same underlying code.

Labels: , ,


Comments: Post a Comment

Subscribe to Post Comments [Atom]





<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]