Problem
The problem / background
I have a project, BusinessProject, that currently stores some static data in memory using the Singleton pattern – we’ll call this class GlobalData
. This project is used in multiple applications, with different requirements on what data should be loaded into memory. One application, lets call this SubProject, only needs a subset of the data. The other project, MasterProject, calls SubProject as well as other functions within BusinessProject which require other data in GlobalData
to be available in memory. My goal is to use inheritance to avoid storing the overlapping data twice, as well as let the project interfacing with BusinessProject easily define the requirements needed by simply calling the desired class.
Simplified Code
public class GlobalData
{
protected static readonly GlobalData _Instance = new GlobalData();
protected DateTime _lastUpdateDate = DateTime.MinValue;
public Dictionary<string, class> Lookup { get; protected set; }
public IList<DateTime> Dates { get; set; }
public Dictionary<string, List<double>> DataSeries { get; protected set; }
static GlobalData() { }
private GlobalData() { }
// each time the Instance requested, make sure the data doesn't need to be refreshed
public static GlobalData Instance
{
get
{
if (!DateTime.Today.Date.Equals(_Instance._lastUpdateDate.Date))
_Instance.LoadData();
return _Instance;
}
}
protected virtual void LoadData()
{
...
_lastUpdateDate = DateTime.Today;
}
}
public class MasterData : GlobalData
{
protected static new readonly MasterData _Instance = new MasterData();
... //extra data properties
static MasterData() { }
private MasterData() :base() {}
protected override void LoadData()
{
base.LoadData();
... // load extra data properties
}
}
Conclusion
I’m looking for any feedback on my implementation of the problem ! Thank you.
Solution
If the objective is to avoid duplicating information in memory, the code you have given won’t archive it.
The new
keyword hides the original value. It doesn’t replace it. You should try another approximations, like the Decorator pattern: https://en.wikipedia.org/wiki/Decorator_pattern
The MasterData inherits from the GlobalData class and stores internally the reference to that class. Whenever someone accesses to a property of the GlobalData class, you redirect the request to the instance stored internally.
The MasterData class stores only the values of the newly added properties.
The tricky part would be preventing other parts of your MasterApplication app calling to the GlobalData class and thus creating another instance.
Singletons are always a nightmare…