To put this in concise language…
Aim:
To create a class which can load and save a list of objects to/from a data source.
Current Method:
I have created a class which accepts two delegates as construction parameters:
private class Foo
{
public delegate List<object> LoadObjectsDelegate();
public delegate void SaveObjectsDelegate(List<object> data);
private LoadObjectsDelegate _loadDelegate;
private SaveObjectsDelegate _saveDelegate;
public Foo(LoadObjectsDelegate loadDelegate, SaveObjectsDelegate saveDelegate)
{
_loadDelegate = loadDelegate;
_saveDelegate = saveDelegate;
}
public List<object> Objects {get; private set;}
public void Load()
{
Objects = _loadDelegate.Invoke();
}
public void Save()
{
_saveDelegate.Invoke(Objects);
}
}
i was wondering if there was a cleaner way to do this.
By the looks of it i’d say you’re trying to implement the Repository pattern, with some extended functionality. I also see no point in trying to inject the load and save logic, as it’s the repository’s job to implement them. If the logic of loading and saving objects is the same for all objects in your domain, have it implemented in a base class, and override it in derived classes if needed. This article on SO could give you some ideas on how to deal with this pattern.