I've got a singleton class like this.
class UserInteraction
{
private CustomerInformation _loginDetails;
private MusicDetails[] _musicFilesDownloaded;
private static volatile UserInteraction _interactionObject = null;
private static object syncRoot = new Object();
private UserInteraction()
{
}
public static UserInteraction Instance
{
get
{
if (_interactionObject == null)
{
lock (syncRoot)
{
if (_interactionObject == null)
_interactionObject = new UserInteraction();
}
}
return _interactionObject;
}
}
public CustomerInformation UserInfo
{
get
{
return _loginDetails;
}
set
{
_loginDetails = value;
}
}
public MusicDetails[] FilesDownloaded
{
get
{
return _musicFilesDownloaded;
}
set
{
_musicFilesDownloaded= value;
}
}
public void PurgeContents()
{
}
public void SerializeValues()
{
}
}
I can use the following code to access this singleton class
UserInteraction.Instance.UserInfo.CardData = "";
My questions are as follows
1) As you can see I can read/write into UserInfo structure, that means i can any number of copy of UserInfo. Is this against the laws of SingleTon?
2) If this is against the law of Singleton, how can i prohibit the duplication of UserInfo at the same time assign values into it?
Thanks.
I think these will guide you to answer your own questions:
In short, the Singleton guarantees that you have only one instance of a given class shared among your system modules. Perhaps should you consider make UserInfo a singleton too? That is only a matter of design, since two different developers will have multiple ways to achieve the same end-behaviour.
This is a singleton. One and only one instance. Thus its not against the laws, I dont think you have a valid question.
This is a singleton on UserInteraction, not on UserInfo. If you need UserInfo to be a singleton, then you need to refactor.
No, this is not against the "laws" of Singleton. A singleton guarantees, that you have at most one instance of a certain class. That you can change the members of that class doesn't matter.
BTW: There are better ways to implement a singleton. See here: http://csharpindepth.com/Articles/General/Singleton.aspx
UserInteraction
is a singleton.UserInfo
is probably no singleton. There can be only one instance ofUserInteraction
per AppDomain, so it is a singleton.You have global mutable state which is evil. So I wouldn't write code like that.
I'm not sure if the check-lock-check pattern is guaranteed to work in .net. But why do you use something complicated like this when you can simply use
Lazy<T>
in .net 4? http://csharpindepth.com/Articles/General/Singleton.aspx