public class Factory { //create static instance of Factory private static Factory factory; private Factory() { //default constructor // since it is private, no other classes can create an object of this class // however, this Factory, and only this Factory class, CAN create it } public static Factory GetInstance() { //create Factory object //if Factory does not exists, create it; else return existing object if (factory == null) { factory = new Factory(); } return factory; } } //end of Factory class
//Controller method public ActionResult FactoryPattern() { //instantiate new Factory instances Factory sing1 = Factory.GetInstance(); Factory sing2 = Factory.GetInstance(); ViewBag.Sing1 = sing1; ViewBag.Sing2 = sing2; ViewBag.Sing1Hash = sing1.GetHashCode(); ViewBag.Sing2Hash = sing2.GetHashCode(); return View(); } //end of controller method //FactoryPattern 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="dvFactory" data-toggle="modal" data-target="#modalFactory" 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="dvFactory1" data-toggle="modal" data-target="#modalFactory1" class="row text-center"><h2>Interface with ascending method</h2></div> @if (ViewBag.Sing1 != null) { <div class="row" style="padding-left:25px;"> 1st Factory is not null: hashcode = ViewBag.Sing1Hash </div> } else { <dv class="row" style="padding-left:25px;">1st Factory is null</dv>} </div> <div class="col-sm-1"></div> <div class="col-sm-5" style="border:2px solid fuchsia;"> <div id="dvFactory2" data-toggle="modal" data-target="#modalFactory2" class="row text-center"><h2>Interface with descending method</h2></div> @if (ViewBag.Sing2 != null) { <div class="row" style="padding-left:25px;"> 2nd Factory is not null: hashcode = ViewBag.Sing2Hash </div> } else { <dv class="row" style="padding-left:25px;">2nd Factory is null</dv>} </div> <div class="col-sm-1"></div> <div class="row" style="height:40px;"></div>