Look at the code below and put the breakpoint on line
if (_s == null)
observe the behavior when we do something like
s2 = Singleton.getSingletonInstance();
using System;
namespace Pattern
{
class Program
{
static void Main(string[] args)
{
Singleton s1, s2;
s1 = Singleton.getSingletonInstance();
s1.instanceCount = 100;
s2 = Singleton.getSingletonInstance();
}
}
sealed class Singleton
{
private static Singleton _s = null;
public int instanceCount;
private Singleton()
{
}
public static Singleton getSingletonInstance()
{
if (_s == null)
{
_s = new Singleton();
}
return _s;
}
}
}
When the breakpoint will hit, try watching the value of _s. The watch window will pop endlessly all over the screen when you click on the following + sign next to the static members icon.
Screenshot:
No comments:
Post a Comment