public class Singleton
{
//create static instance of Singleton
private static Singleton singleton;
private Singleton()
{
//default constructor
// since it is private, no other classes can create an object of this class
// however, this Singleton, and only this Singleton class, CAN create it
}
public static Singleton GetInstance()
{
//create Singleton object
//if Singleton does not exists, create it; else return existing object
if (singleton == null)
{
singleton = new Singleton();
}
return singleton;
}
}//end of Singleton class
//Controller method
public ActionResult SingletonPattern()
{
//instantiate new Singleton instances
Singleton sing1 = Singleton.GetInstance();
Singleton sing2 = Singleton.GetInstance();
ViewBag.Sing1 = sing1;
ViewBag.Sing2 = sing2;
ViewBag.Sing1Hash = sing1.GetHashCode();
ViewBag.Sing2Hash = sing2.GetHashCode();
return View();
}//end of controller method
//SingletonPattern html
<div class="row col-sm-12 text-center"><h4 style="color:red;">(click on headings for code snippets)</h4>
</div>
<div class="row col-sm-12">
<div class="col-sm-4"></div>
<div id="dvSingleton" data-toggle="modal" data-target="#modalSingleton" class="row text-center col-sm-4"><h1>Interface</h1></div>
<div class="col-sm-4"></div>
</div>
<div class="rowcol-sm-12">
<div class="col-sm-5" style="border:2px solid fuchsia;">
<div id="dvSingleton1" data-toggle="modal" data-target="#modalSingleton1" class="row text-center"><h2>Interface with ascending method</h2></div>
@if (ViewBag.Sing1 != null)
{
<div class="row" style="padding-left:25px;">
1st Singleton is not null: hashcode = ViewBag.Sing1Hash
</div>
}
else
{ <dv class="row" style="padding-left:25px;">1st Singleton is null</dv>}
</div>
<div class="col-sm-1"></div>
<div class="col-sm-5" style="border:2px solid fuchsia;">
<div id="dvSingleton2" data-toggle="modal" data-target="#modalSingleton2" class="row text-center"><h2>Interface with descending method</h2></div>
@if (ViewBag.Sing2 != null)
{
<div class="row" style="padding-left:25px;">
2nd Singleton is not null: hashcode = ViewBag.Sing2Hash
</div>
}
else
{ <dv class="row" style="padding-left:25px;">2nd Singleton is null</dv>}
</div>
<div class="col-sm-1"></div>
<div class="row" style="height:40px;"></div>