1. Start with the "simplest" Singleton mode:
Public class Singleton
{
Private static Singleton instance = null;
Private static readonly object syncRoot = new object ();
Private Singleton ()
{
}
Public static Singleton GetInstance ()
{
If (instance = null)
{
Lock (syncRoot)
{
If (instance = null)
{
Instance = new Singleton ();
}
}
}
Return instance;
}
}
People who have a better understanding of the basic knowledge of the design model should be familiar with the above Code. During the last interview, the examiner asked Lou pig to write a ticket. Although I have not deliberately used the design mode for programming for a long time, but for this Singleton mode, haha, although the Big husband is not angry with the color, however, at that time, the pig in the nc building was very eager to deliver the above answer. The interviewer gave me a few comments and asked, can the object instance in lock be directly replaced by instance? Whether a new object is redundant can be written in the following form:
Public class Singleton
{
Private static Singleton instance = null;
// Private static readonly object syncRoot = new object ();
Private Singleton ()
{
}
Public static Singleton GetInstance ()
{
If (instance = null)
{
Lock (instance) // can an instance replace syncRoot?
{
If (instance = null)
{
Instance = new Singleton ();
}
}
}
Return instance;
}
}
Even before this question, the interviewer asked a database design question and a few small questions about c # (I had a question that I was saying that it was "amazing", so I was afraid of it) I am very aware of the depth and cultivation of knowledge. Lou pig is already very cautious, but this problem still makes Lou pig feel confused again. No one has ever asked Lou pig this question before, Lou pig has never taken the initiative to think about it, his head is white, just want to calm down, the interviewer asked the same question again